2

I have a multivalue entity reference field, referencing basic content. The content (node) view is controlled via display modes (display modes is probably not relevant to the question)

Right now the entity reference field template is 'boilerplate' and just outputs the content in a for loop.

{% for item in items %}    
    {{ item.content }}
{% endfor %} 

My display node template, node--[content type]--[display mode].tpl.twig has custom markup, and granular output of field values.

However somewhere 'deep' in this template I need to alter the markup in accordance with the position this node has in the parent referencing entity.

i.e.

  • entity reference field:
    • node 1
    • node 2
    • node 3 <-- pass this list position value somehow into the child node template, so i can change the markup inside
    • node 4

I've been stepping through preprocessor variables in node_preprocess and field_preprocess, but I'm not really clear if the child node is 'aware' of its parent field, or more importantly the hierarchy of the parent field, and its position in it.

Any help or pointers much appreciated!

1

well, this seems to be working.

function THEME_preprocess_node(&$variables) {
$nid  = $variables['node']->id();

if ($variables['elements']['#view_mode'] === 'VIEW_MODE') {
// Get the node ID.
    $variables['nid'] = $nid;
    $parent   = $variables['elements']['#node']->_referringItem->getEntity();
    $items = $parent->get('FIELD_NAME')->getValue();

    foreach ($items as $key => $item) {
        if ($item['target_id'] == $nid) {
            $variables['tree_position'] = $key;
        }
    }
  }
}

Not sure this is the best way. So any suggestions still welcome.

  • 1
    note this will fail if your entity reference field has multiple values with the same NID. – baku Sep 23 '17 at 20:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.