Add a field using baseFieldDefinitions()

Created on 24 November 2024, 28 days ago

Problem/Motivation

I have a custom entity type and I want to add a state field to it. Is it possible to add it directly in the entity class? Thanks to that I can have all data in a single db table.

Proposed resolution

So the entity class would look like this:


final class Magic extends ContentEntityBase implements AktInterface {

  // ...

  /**
   * {@inheritDoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type): array {
    $fields = parent::baseFieldDefinitions($entity_type);

    // ...

    $fields['state'] = BaseFieldDefinition::create('state')
      ->setLabel(t('State'))
      ->setSettings([
        // ???
      ])
      ->setDisplayOptions('form', [
        // ???
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        // ???
      ])
      ->setDisplayConfigurable('view', TRUE);

    return $fields;
  }

}

Is it possible now? Or we should wait for some module updates?

Feature request
Status

Active

Version

1.12

Component

Code

Created by

🇷🇺Russia i-grou

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

  • Issue created by @i-grou
  • 🇮🇱Israel jsacksick

    Ofc, take a look at the order entity type defined by Drupal commerce for example:

       $fields['state'] = BaseFieldDefinition::create('state')
          ->setLabel(t('State'))
          ->setDescription(t('The order state.'))
          ->setRequired(TRUE)
          ->setSetting('max_length', 255)
          ->setDisplayOptions('view', [
            'label' => 'hidden',
            'type' => 'state_transition_form',
            'settings' => [
              'require_confirmation' => TRUE,
              'use_modal' => TRUE,
            ],
            'weight' => 10,
          ])
          ->setDisplayConfigurable('form', TRUE)
          ->setDisplayConfigurable('view', TRUE)
          ->setSetting('workflow_callback', ['\Drupal\commerce_order\Entity\Order', 'getWorkflowId']);
  • Automatically closed - issue fixed for 2 weeks with no activity.

Production build 0.71.5 2024