I created a custom Entity, using the following code in the CustomEntity.php file.

public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
  $fields = parent::baseFieldDefinitions($entity_type);

  $fields['name'] = BaseFieldDefinition::create('string')
      'max_length' => 50,
      'text_processing' => 0,
    ->setDisplayOptions('view', [
      'label' => 'above',
      'type' => 'string',
      'weight' => -4,
    ->setDisplayOptions('form', [
      'type' => 'string_textfield',
      'weight' => -4,
    ->setDisplayConfigurable('form', TRUE)
    ->setDisplayConfigurable('view', TRUE);

  return $fields;

We can add fields for the entity and all bundles will automatically inherit them.

I set a bundle in the myModule/config/install/myModule.customEntity.bundleA.yml file.

uuid: db129d12-849a-4e68-bb56-d787b4b0cf42
langcode: en
status: true
dependencies: {  }
id: bundleA
label: bundleA

How can I programmatically add fields to that bundle?


1 Answer 1


An entity class can implement FieldableEntityInterface::bundleFieldDefinitions() to add fields to a bundle, but as that documentation page says, the recommended approach is another one.

This function can return definitions both for bundle fields (fields that are not defined in $base_field_definitions, and therefore might not exist on some bundles) as well as bundle-specific overrides of base fields (fields that are defined in $base_field_definitions, and therefore exist for all bundles). However, bundle-specific base field overrides can also be provided by 'base_field_override' configuration entities, and that is the recommended approach except in cases where an entity type needs to provide a bundle-specific base field override that is decoupled from configuration.

As for decoupling the bundle fields from the configuration, the same page says:

Note that for most entity types, the bundles themselves are derived from configuration (e.g., 'node' bundles are managed via 'node_type' configuration entities), so decoupling bundle-specific base field overrides from configuration only makes sense for entity types that also decouple their bundles from configuration.

Finalize API for creating, overriding, and altering code-defined bundle fields could change how bundle fields are created. That issue isn't yet marked as fixed, and it has been opened 8 years ago.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.