I created an entity using drupal console and now I would like to add fields to it. These should be references to other entities. I want these fields to be added programmatically, in the code. Ideally in the entity class so I can use entity methods to load referenced entities. How do I do that?


1 Answer 1


When you create an entity using Drupal Console you'll find such a field as example already defined in baseFieldDefinitions(), which references the user entity:

$fields['user_id'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Authored by'))
  ->setDescription(t('The user ID of author of the {{ label }} entity.'))
  ->setSetting('target_type', 'user')
  ->setSetting('handler', 'default')
  ->setDisplayOptions('view', [
    'label' => 'hidden',
    'type' => 'author',
    'weight' => 0,
  ->setDisplayOptions('form', [
    'type' => 'entity_reference_autocomplete',
    'weight' => 5,
    'settings' => [
      'match_operator' => 'CONTAINS',
      'size' => '60',
      'autocomplete_type' => 'tags',
      'placeholder' => '',
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

You can define as target other entities:

  ->setSetting('target_type', 'my_other_entity')

BTW the two last two lines of the example make this base field configurable in UI. You can set this to FALSE if you don't want that anyone can change the configuration you've made in code.

You can customize this, for example if you want a dropdown select element:

  ->setDisplayOptions('form', [
    'type' => 'options_select',
    'weight' => 5,
    'settings' => [

To implement code to load the referenced entities extend the field widget OptionsSelectWidget, add a custom plugin id to the annotations my_options_select, which you can use for the type in the example above

    'type' => 'my_options_select',

and override the plugin methods to load the options. For simple cases use hook_options_list_alter, this hook is invoked by the widget base class method getOptions().

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.