Skip to content

Instantly share code, notes, and snippets.

@tombola
Forked from zerolab/example.module.php
Last active March 17, 2017 13:29
Show Gist options
  • Save tombola/d40d59d3f93ddca796a6a1e1c6302f3f to your computer and use it in GitHub Desktop.
Save tombola/d40d59d3f93ddca796a6a1e1c6302f3f to your computer and use it in GitHub Desktop.
Drupal 8 pass data down ER fields
<?php
/**
* @file
* An example of how to pass the item number from a multi-value
* entityreference field to the entities concerned.
*/
/**
* Implements hook_preprocess_field().
* Change `field_name` to your field machine name.
*/
function example_preprocess_field__field_name(&$variables) {
foreach ($variables['items'] as $key => $item) {
$variables['items'][$key]['content']['#field_item_number'] = $key + 1;
}
}
/**
* Implements hook_preprocess_node().
*/
function example_preprocess_node(&$variables) {
if (isset($variables['elements']['#field_item_number'])) {
$variables['field_item_number'] = $variables['elements']['#field_item_number'];
}
}
{#
// .. usual template stuff
#}
<article>
{% if field_item_number %}
This is item number {{ field_item_number }} in the field which references it.
{% else %}
{{ content }}
{% endif %}
</article>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment