0

I have two content types - A and B. For content type A, there are 5 content items - Aa, Ab, Ac, Ad, Ae. For content type B, I have two items Ba, Bb. Content type B has a field that is an entity reference of content type A. In a single page I have the following setup:

Ba -> Aa, Ab, Ac, Ad, Ae
Bb -> Aa, Ab, Ac, Ad, Ae

I have a twig template for B and a separate one for A. When rendering Aa - Ae, I need to know if the container node is Ba or Bb because it is rendered differently. Ba and Bb know about the referenced entities (Aa - Ae), but the referenced entities don't know who their parent is.

I've tried using the preprocessor but I can't seem to find a way to get the parent (containter) node.

Any suggestions?

TIA.

3
  • These types of relations are often done with Views, you can create a Block for example that is showing either the children of the current node or the parents of the current node. I think the most common way of labeling these connections is that your Bs would be children and As would be parents.
    – prkos
    Commented May 21, 2020 at 23:47
  • Following that last logic would mean creating 10 nodes of type A rather than just the 5 used twice, right? Commented May 22, 2020 at 12:55
  • No, I guess I didn't express myself clear enough. I was just commenting on which "sides" to call a child or a parent, as commonly used in articles. There are many tutorials about relations through ER fields so I wanted to warn about the perspective if you decide to investigate further in that direction :)
    – prkos
    Commented May 23, 2020 at 0:30

1 Answer 1

3

You should be able to do this:

$loaded_nodes = \Drupal::entityTypeManager()->getStorage('node')->loadByProperties([
  'field_node_reference' => $node->id(),
]);
$parent_node = reset($loaded_nodes);

Replace the field name with your actual field name.

2
  • How to render parent node field values on the template file. Commented Jul 30, 2022 at 15:18
  • You would need to implement the above in a preproccess function for the template.
    – Jaypan
    Commented Jul 30, 2022 at 19:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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