Skip to main content

Drupal 8-9: Getting the term object from hook preprocess term reference field

This is how you load the term object from a hook preprocess term reference field and get the value of a custom field. In my case i want to get the custom color each category term has.

function mytheme_preprocess_field__node__field_custom(&$vars) {
  //We can have more that one categories
  $current_first_tid = $vars['element']['#object']->get('field_main_category')->first()->target_id;
  $term_obj = Drupal::entityTypeManager()->getStorage('taxonomy_term')->load($current_first_tid);
  $cat_color = $term_obj->get('field_category_color')->value;
  //Make sure we always return a default color hex value
  $vars['cat_color'] = isset($cat_color) ? $cat_color : '#cc0000';
}

 

custom module

Latest Articles

VSCode Drupal Coding Standards Setup (From Scratch) admin_pixelthi… Mon, 12/22/2025 - 16:01 VSCode Drupal Coding Standards Setup (From Scratch)

VSCode Drupal Coding Standards Setup (From Scratch)

vscode
Using drupal/core-composer-scaffold to prevent rewriting .htaccess or robots.txt file admin_pixelthi… Sun, 12/01/2024 - 16:49 Using drupal/core-composer-scaffold to prevent rewriting .htaccess or robots.txt file

Using drupal/core-composer-scaffold to prevent rewriting .htaccess or robots.txt file

composer
Controlling ckeditor styling options with hook_editor_js_settings_alter admin_pixelthi… Thu, 05/16/2024 - 10:49 Controlling ckeditor styling options with hook_editor_js_settings_alter

Controlling ckeditor styling options with hook_editor_js_settings_alter

php hook hook_editor_js_settings_alter hook_field_widget_single_[WIDGET_TYPE]_form_alter