3

I have an Entity: EntityX. It installs correctly and works the way that I want it to; with, of course, one exception.

I want to attach an entity reference to a specific vocabulary. I have tried:

My vocabulary's machine name is: custom_vocabulary

In EntityX's definition I have the following defined in the baseFieldDefinitions function:

$fields['my_custom_vocabulary'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Vocabulary'))
  ->setDescription(t('What was this tagged with.'))
  ->setSetting('target_type', 'custom_vocabulary')
  ->setSetting('handler', 'default')
  ->setDisplayOptions('view', array(
    'label' => 'above',
    'type' => 'author',
    'weight' => -3,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'entity_reference_autocomplete',
    'settings' => array(
      'match_operator' => 'CONTAINS',
      'size' => 60,
      'placeholder' => '',
    ),
    'weight' => -3,
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

But when I go to install it, I get the following error:

Drupal\Component\Plugin\Exception\PluginNotFoundException: The "custom_vocabulary" entity type does not exist. in /brew/www/html/core/lib/Drupal/Core/Entity/EntityTypeManager.php:133

While looking at the article defined in the installation profile for Drupal, I see that they use it as a field and not a true entity reference. Is there no way for me to do it this way? I can't have this all nicely bundled into one single entity.

What I don't know how to do is add a term from a vocabulary to an entity type.

1 Answer 1

7

Vocabularies are bundles of the entity type taxonomy term. If you want to reference a vocabulary then first set taxonomy_term as target type and second restrict the field to a specific vocabulary as target bundle:

$definition = BaseFieldDefinition::create('entity_reference')
  ->setSetting('target_type', 'taxonomy_term')
  ->setSetting('handler_settings', ['target_bundles' => ['custom_vocabulary' => 'custom_vocabulary']]);

See change record https://www.drupal.org/node/2576151

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.