0

I have a paragraph called Boxes which is a parent paragraph referencing to many paragraphs of type Box. I have written the preprocess function of paragraph Boxes which contains some logic that can't be done elsewhere. The result of that code is stocked in a variable called custom_color_weight.

I wanna access this variable in the box paragraph template but I can't move the code that yielded that variable's value outside the preprocess boxes function.

I was searching for a way to pass the variable from preprocess boxes to the preprocess box and hence to the template of the box paragraph Is there any way to do it?

Ps : I can't use getParentEntity in the preprocess Box function to get each time the parent Boxes entity and calculate the value of custom_color right there because that way I will be loading the parent paragarph entity multiple times as I have multiple nested paragraphs of type Box inside the paragraph Boxes.

1 Answer 1

1

getParentEntity() is not the problem, it always returns a reference to the same instance. There you could use a bundle class to calculate and store the value. See this change record:

https://www.drupal.org/node/3191609

Then you can replace both preprocess hooks by calling the bundle class method directly from the child Twig template

{{ paragraph.getparententity.getcustomcolor }}

where getCustomColor() is a method of the parent bundle class.

3
  • But if i use getParententity it doesn't load the parent paragraph again and again ? I didn't understand how it just returns a reference :) Thankk you Commented Oct 18, 2023 at 5:29
  • In drupal 9 and 10 getParentEntity loads the parent entity before returning it Commented Oct 18, 2023 at 5:37
  • 1
    Entity objects are cached in memory and loading the entity again returns the cached instance. This is based on PHP passing objects always by reference.
    – 4uk4
    Commented Oct 18, 2023 at 6:53

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.