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>'))
  ->setSetting('target_type', 'taxonomy_term')
  ->setSetting('handler', 'default')
  ->setSetting('handler_settings', $handler_settings)
  ->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)
  • I'm not sure where you have this code, but you're not actually saving anything here so that could be the problem. – sonfd Jun 30 at 13:02
  • It's called in a Ajax callback from a form.BaseFieldDefinition::create shouldn't need a save – JAyenGreen Jun 30 at 13:05
  • You can't save this code, it is for adding a base field to an entity type and it needs to be run either in the entity class itself or in hook_entity_base_field_info(). – 4k4 Jun 30 at 13:11
  • If you want to add a bundle field to a content type you have to save it as configuration, see drupal.stackexchange.com/questions/222260/… – 4k4 Jun 30 at 13:12
  • It says that the easiest way is to use config, but that isn't an option in my use case, and I'm assuming that when adding a field via the UI, it's doing it without config. – JAyenGreen Jun 30 at 13:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.