Retrieve a taxonomy term in the buildrow function of a drupal 8 custom entity

六月ゝ 毕业季﹏ 提交于 2019-12-12 04:02:53

问题


I have built a custom entity that works well. One of my fields is a taxonomy but I can not retrieve the name of the term in the buildRow(EntityInterface $entity) function which displays my records.

For a simple string field I do: $row['foo'] = $entity->foo->value;

How to do a taxonomy term that is an entity_reference: $row['bar'] = $entity->BAR_TERM_NAME;

Thank you for your help.


回答1:


To work as requested you need 3 things:

  1. Implements an entity_reference field in your custom Entity.
  2. Add a getter methode for you field.
  3. Retrieve your field in your custom ListBuilder -> buildRow().

Check the Drupal 8 documentation about FieldTypes, FieldWidgets and FieldFormatters.


Implements an entity_reference field

Your field foo in your Entity should be generated using the entity_reference field type.

public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
  // Some code ...

  $fields['foo'] = BaseFieldDefinition::create('entity_reference')
    ->setLabel($this->t('Foo field'))
    ->setDescription($this->t('The Foo field.'))
    ->setSetting('target_type', 'taxonomy_term')
    ->setSetting('handler', 'default')
    ->setSetting('handler_settings', ['target_bundles' => ['vocabulary_id' => 'vocabulary_id']])
    ->setDisplayOptions('view', [
      'label'  => 'hidden',
      'type'   => 'vocabulary_id',
      'weight' => 0,
    ])
    ->setDisplayOptions('form', [
      'type'     => 'options_select',
      'weight'   => 40,
    ])
    ->setDisplayConfigurable('form', TRUE)
    ->setDisplayConfigurable('view', TRUE);

  // Some code ...
}

You should then replace the 3 vocabulary_id by the vocabulary that you wanna links.

Add a getter

In the same Class as your baseFieldDefinitions.

// Some code ...
public function getFoo() {
  return $this->get('foo')->value;
}
// Some code ...

Retrieve the field

In your ListBuilder Class.

public function buildRow(EntityInterface $entity) {
  // Some code ...
  $row['foo']   = $entity->getFoo();

  // Some code ...
}

Hopes it will help you !



来源:https://stackoverflow.com/questions/45508304/retrieve-a-taxonomy-term-in-the-buildrow-function-of-a-drupal-8-custom-entity

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!