✍️
Dev Patterns
  • Dev Patterns: Introduction
  • Drupal 8
    • Form Alter
      • data-twig-suggestion preprocess
      • Address field #after_build
    • Language
      • Language direction classes
      • Set twig variables for languages
      • Get the language direction (PHP)
    • Routes
      • Alter page title based on route
    • Preprocess Page
      • Preprocess users
      • Check if a node has body content and create a variable
    • Preprocess HTML
      • Check node ids and field values in preprocess_html
      • Add a body class based on route
    • General Theming
      • Preprocess Paragraph
      • Paragraph theme hook for a specific field value
      • Field theme hook suggestion based on the entity string
    • Twig
      • Twig include file
      • Twig loops
      • Loop index
    • Page alter
      • Page title theme hook
      • Page content type theme hook
      • Region alter
    • Users
      • Twig user variables
      • User view mode theme hook
    • Fields
      • Replace field name
      • Count number in a multi-value field array
    • Terminal
      • Query block ids for use with twig tweak
      • Check for available updates in terminal
  • Drupal 7
    • Create View modes programtically
    • Node form alter
    • Element Children
Powered by GitBook
On this page

Was this helpful?

  1. Drupal 7

Element Children

Element Children is a great way to dig into arrays with multiple keys

This might appear under a pre-process node

/**
 * Override or insert vars into the node template.
 */
function nrdc_preprocess_node(&$vars) {
  // Define the node.
  $node = $vars['node'];
  $nodetype = $node->type;

  // Retrive terms on node and loop through each term
  // using a $key in place of the array number.
  // so that it does not get reset with every pass.
  // The array might look something like this in Xdebug
  // $vars['field_issue_term']['0']['taxonomy_term']
  // $vars['field_issue_term']['1']['taxonomy_term']
  // etc...
  // Set the linked_terms variable to false before the loop.
  $vars['linked_terms'] = FALSE;
  // Loop using a key value via element_children.
  foreach (element_children($vars['field_issue_term']) as $key) {
    // Get the term name.
    $term_name = $vars['field_issue_term'][$key]['taxonomy_term']->name;
    // Get the term TID.
    $term_tid = $vars['field_issue_term'][$key]['taxonomy_term']->tid;
    // Convert the term path into an alias.
    $term_url = drupal_lookup_path('alias', 'taxonomy/term/' . $term_tid);
  }
}
PreviousNode form alter

Last updated 5 years ago

Was this helpful?