Drupal - 获取自定义分类字段

Drupal - Get custom taxonomy fields

我正在尝试获取分配给分类法的自定义字段。我试过这个:

$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
    );
  }

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

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

bool $load_entities: If TRUE, a full entity load will occur on the term objects. Otherwise they are partial objects queried directly from the {taxonomy_term_data} table to save execution time and memory consumption when listing large numbers of terms. Defaults to FALSE.

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

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

从这个 post 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,
    );
}

很有用!

public 函数 getTaxonomyBuild(){ $terms = \Drupal::service('entity_type.manager')->getStorage("taxonomy_term")->loadTree('faq_sec');

foreach($terms as $term) {
  $term_data[] = array(
    'name' => $term->name,
    'img' => file_create_url(\Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($term->tid)->get('field_sec_img')->entity->uri->value),
  );
}
    return $term_data;  
}

很好的解决方案