【问题标题】:Drupal - Get custom taxonomy fieldsDrupal - 获取自定义分类字段
【发布时间】:2018-08-20 08:18:05
【问题描述】:

我正在尝试将自定义字段分配给分类。我试过这个:

$vid = 'zeme';
$terms =\Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid);

$terms 现在存储名为“zeme”的词汇表中的所有术语。问题是当我打印这个变量时,它没有显示我需要获取的自定义字段。 知道如何获得这个自定义字段吗? 我的代码如下所示:

 $vid = 'zeme';
  $terms =\Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid); 
  foreach ($terms as $term) {
    $term_data[] = array(
      'id' => $term->tid,
      'name' => $term->name
    );
  }

【问题讨论】:

    标签: arrays drupal-8 drupal-taxonomy


    【解决方案1】:

    这里是loadTree function 官方文档: TermStorage::loadTree

    当您使用loadTree 函数时,它只会为您获取最少的数据以节省执行时间。可以看到有一个$load_entities参数默认设置为false

    bool $load_entities:如果为 TRUE,则将在 术语对象。否则它们是直接从 {taxonomy_term_data} 表以节省执行时间和内存 列出大量条款时的消费。默认为 FALSE。

    因此,如果您想获取每个分类术语的所有数据,您必须将$load_entities 设置为true

    $vid = 'zeme';
    $terms =\Drupal::entityTypeManager()
      ->getStorage('taxonomy_term')
      ->loadTree($vid, 0, null, true);
    

    【讨论】:

    • 很多数据,但唯一有用的回应,谢谢
    【解决方案2】:

    从这篇帖子Get custom fields assigned to taxonomy找到这种方式:

    $contact_countries = \Drupal::service('entity_type.manager')->getStorage("taxonomy_term")->loadTree('contact_country');
    
    $terms = array();
    
    foreach($contact_countries as $contact_countrie) {
        $terms[] = array(
            'contact_country' => $contact_countrie->name,
            'contact_phone' => \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($contact_countrie->tid)->get('field_phone')->getValue()[0]['value'],
            'contact_flag' => \Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($contact_countrie->tid)->get('field_category_flag')->entity->uri->value,
        );
    }
    

    很有用!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多