【问题标题】:Retrieve a taxonomy term in the buildrow function of a drupal 8 custom entity在 drupal 8 自定义实体的 buildrow 函数中检索分类术语
【发布时间】:2017-08-04 13:36:28
【问题描述】:

我已经构建了一个运行良好的自定义实体。我的一个字段是分类,但我无法在显示我的记录的 buildRow(EntityInterface $entity) 函数中检索术语的名称。

对于一个简单的字符串字段,我这样做:$row['foo'] = $entity->foo->value;

如何做一个作为 entity_reference 的分类术语:$row['bar'] = $entity->BAR_TERM_NAME;

感谢您的帮助。

【问题讨论】:

    标签: drupal-8


    【解决方案1】:

    要按要求工作,您需要 3 样东西:

    1. 在您的自定义实体中实现 entity_reference 字段。
    2. 为您的字段添加一个 getter 方法。
    3. 在您的自定义 ListBuilder -> buildRow() 中检索您的字段。

    查看有关 FieldTypes, FieldWidgets and FieldFormatters 的 Drupal 8 文档。


    实现 entity_reference 字段

    您的实体中的字段 foo 应使用 entity_reference 字段类型生成。

    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 ...
    }
    

    然后,您应该将 3 个 vocabulary_id 替换为您想要链接的词汇。

    添加一个吸气剂

    与您的 baseFieldDefinitions 在同一类中。

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

    检索字段

    在您的 ListBuilder 类中。

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

    希望对你有帮助!

    【讨论】:

    • 很高兴为您提供帮助,欢迎来到 Stack Overflow。如果此答案或任何其他答案解决了您的问题,请将其标记为已接受。这将帮助人们在页面上看到好的答案,这也有助于贡献者将注意力集中在仍然没有答案的旧 SO。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-02
    • 1970-01-01
    • 1970-01-01
    • 2016-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多