Adam Šulc
Adam Šulc

Reputation: 546

Drupal - Get custom taxonomy fields

I am trying to get a custom field assigned to taxonomy. I have tried this:

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

$terms is now storing all the terms from the vocabulary called 'zeme'. The problem is when I print this variable, it doesnt show the custom field that I need to get. Any idea how can I get this custom field? My code looks like this:

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

Upvotes: 2

Views: 3724

Answers (3)

Abdelwahied Ali
Abdelwahied Ali

Reputation: 1

public function 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;  
}

good solution

Upvotes: 0

Pistis Valentino
Pistis Valentino

Reputation: 143

Found this way from this 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,
    );
}

Very usefull!

Upvotes: 0

Corentin Le Fur
Corentin Le Fur

Reputation: 338

Here is the loadTree function official documentation : TermStorage::loadTree

When you use the loadTree function, it will only get you the minimal datas to save execution time. You can see there is a $load_entities parameter set to false by default.

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.

So if you want to get all the datas of each of your taxonomy terms, you have to set $load_entities to true.

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

Upvotes: 5

Related Questions