Categories
CMS Drupal Mastering Development

How to create a term reference field programmatically

I need to add a taxonomy reference field to a node bundle, programmatically.

I found a couple examples here, but one actually is incorrectly titled and is about creating a from field for it, and the other is from 2012.

I have tried the following, based on the couple of suggested examples I found, and a further suggestion that one use the field/field storage export as a guide.

When it runs, it silently fails. The field is not created, nor is there an error thrown.

use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\Entity\FieldConfig;

$handler_settings = [
      'target_bundles' => [
        '<vid>' => '<vid>'
      ],
      'sort' => [
        'field' => 'name',
        'direction' => 'asc',
      ],
      'auto_create' => FALSE,
      'auto_create_bundle' => '',
    ];
    

$fields['<field_my_field>'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('<My Field>'))
  ->setDescription(t(''))
  ->setRequired(TRUE)
  ->setSetting('target_type', 'taxonomy_term')
  ->setSetting('handler', 'default')
  ->setSetting('handler_settings', $handler_settings)
  ->setRevisionable(TRUE)
  ->setTranslatable(TRUE)
  ->setDisplayOptions('view', [
    'label' => 'hidden',
    'type' => '<vid>',
    'weight' => 0,
  ])
  ->setDisplayOptions('form', [
    'type' => 'entity_reference_autocomplete',
    'weight' => 5,
    'match_operator' => 'CONTAINS',
  ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE)
  ->setCardinality(1);

Leave a Reply

Your email address will not be published. Required fields are marked *