Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
Problem
On a Twig template, when trying to print some node fields (which are configured as entity references), I'm getting a wrong value if the field is left empty. The wrong value is always the title for the node where the entity is referenced.
For example:
{% if node.field_foo.entity.title.value %}
{{ node.field_foo.entity.title.value|render }}
{% endif %}
You would expect that code to return nothing (ie. the if
evaluates to false
) if the field is left empty when creating new content.
Instead of that, the if
evaluates to true
and the value printed for the variable is the node's title. Ie, as if the code was {{ node.title.value|render }}
.
Comments
Comment #2
maniqui CreditAttribution: maniqui commentedForgot to mention the current workaround I'm applying.
As mentioned previously, when
field_foo
(remember: configured an entity reference) is left empty, for some unknown reason (ie: the bug I'm reporting), thenode.field_foo.entity
"becomes" the parent node itself, and prints the wrong value (in this case, the node'stitle
).I've inspected the field using
kint
and it seems that one way to test if theentity
is a referenced entity is by testing for a_referringItem
attribute. That attribute is only present in true referenced entities, and not on the wrong value (the parent node) I'm getting when the field is left empty.Comment #3
Pranali.addweb CreditAttribution: Pranali.addweb at AddWeb Solution Pvt. Ltd. commentedI reproduce the bug and its working fine on my machine.
Please take a reference to below code. We should trim out the variable value which placing if condition. Sometimes it will take blank spaces and return true. We should trim out unwanted content.
{% if content.field_foo|render|trim %}
Like if we talk about your example you should use
I hope this works for you.
Comment #4
Ivan Berezhnov CreditAttribution: Ivan Berezhnov as a volunteer and at Drupal Ukraine Community for Levi9 commentedComment #5
larowlanItem #3has the fix, adding
|trim
Comment #7
Shifali Baghel CreditAttribution: Shifali Baghel commentedIt worked. Great!!!
Comment #8
Cayenne CreditAttribution: Cayenne commentedWorks for me too. Seems like an awkward fix, but it works for me.
Comment #9
chefigueroa CreditAttribution: chefigueroa commented#3 worked. Thanks!