1

My goal was to create a taxonomy reference field in Drupal 8.2.

Consider these to field definitions on an entity.

    // #1
    $fields[$field] = BaseFieldDefinition::create('entity_reference')
        ->setTargetEntityTypeId('taxonomy_term')

    // #2
    $fields[$field] = BaseFieldDefinition::create('entity_reference')
        ->setSetting('target_type', 'taxonomy_term')

Here is how #1 is documented:

  /**
   * Sets the ID of the type of the entity this field is attached to.
   *
   * @param string $entity_type_id
   *   The name of the target entity type to set.
   *
   * @return $this
   */
  public function setTargetEntityTypeId($entity_type_id) {

Looking at the description both should produce the same result - set target entity type.

The #1 creates me an input with autocomplete from page names and page types.

The #2 creates n input with autocomplete from taxonomy terms.

Why does this happen and what is #1 is meant to do?

1 Answer 1

1

As I answered at Limit Taxonomy Term references to special vocabulary if you want to create a custom entity_reference field on custom entity type try something like

$fields['book_cat'] = BaseFieldDefinition::create('entity_reference')
   ->setLabel(t('LABEL'))
   ->setDescription(t('DESCRIPTION'))
   ->setSetting('target_type','taxonomy_term' )
   ->setSetting('handler','default' )
   ->setSetting('handler_settings',['target_bundles'=>['VOCAB_MACHINE_NAME'=>'VOCAB_MACHINE_NAME']] )
   ->setTranslatable(TRUE)
   ->setDisplayOptions('form', array(
       'type' => 'options_select',
       'weight' => -1,
       'settings' => array(
           'size' => '60',
           'placeholder' => '',
       ),
   ))
   ->setDisplayConfigurable('form', TRUE)
   ->setDisplayConfigurable('view', TRUE);

AND about setTargetEntityTypeId :(Doc)

Sets the ID of the type of the entity this field is attached to.

and used when you want attach field(s) not for referencing.

2
  • Thanks for your answer. Been a while though, so can't test the answer now.
    – Okneloper
    Commented Mar 25, 2017 at 21:00
  • @Okneloper I test it before send here ;)
    – Yuseferi
    Commented Mar 25, 2017 at 21:24

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.