0

I create entity form and add entity reference taxonomy field, set it as select and specify options, but i get all terms instead of one vocabulary terms.

Any idea how to make it works?

here some code.

$taxonomyStorage = \Drupal::entityTypeManager()->getStorage('taxonomy_term');
$voc             = $taxonomyStorage->loadTree("my_vocabulary");

$array = [];

foreach ($terms as $term) {
    $array[] = [
        'tid' => $term->tid,
        'name' => $term->name
    ];
}

$fields['voc_type'] = BaseFieldDefinition::create('entity_reference')
        ->setLabel(t('Voc Type'))
        ->setDescription(t('Voc tag'))
        ->setSetting('target_type', 'taxonomy_term')
        ->setDisplayOptions('form', [
            'type'    => 'select',
            'options' => $array,
            'weight'  => -6,
        ])
        ->setDisplayConfigurable('form', true);
2
  • @Beebee the problem is with Entity form, not reference – Zbigniew Malcherczyk Apr 6 '18 at 14:42
  • Check the answer on that dupe, there's a bit of code there to specify which target_bundles you want to set. That should answer your question, I'm fairly confident. – Beebee Apr 6 '18 at 14:45
1
$fields['voc_type'] = BaseFieldDefinition::create('entity_reference')
    ->setLabel(t('Voc Type'))
    ->setDescription(t('Voc tag'))
    ->setSetting('target_type', 'taxonomy_term')
    ->setDisplayOptions('form', [
        'type'    => 'select',
        'options' => $array,
        'weight'  => -6,
    ])
    ->setDisplayConfigurable('form', true)

    // I think you're missing this:
    ->setSetting('handler', 'default:taxonomy_term')
    ->setSetting('handler_settings', [
      'target_bundles' => [
        'my_vocabulary' => 'my_vocabulary'
      ]
    ]);

I don't think you need to manually gather the options and set them like that. The target_bundles setting should take care of that.

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