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

maniqui created an issue. See original summary.

maniqui’s picture

Forgot to mention the current workaround I'm applying.

            {% if node.field_foo.entity._referringItem %}
                {{ node.field_foo.entity.title.value|render }}
            {% endif %}

As mentioned previously, when field_foo (remember: configured an entity reference) is left empty, for some unknown reason (ie: the bug I'm reporting), the node.field_foo.entity "becomes" the parent node itself, and prints the wrong value (in this case, the node's title).

I've inspected the field using kint and it seems that one way to test if the entity 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.

Pranali.addweb’s picture

I 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 %}

{{ content.field_foo }}
    {% else %}
      {{' do something'}}
{% endif %} -->It will work fine.

Like if we talk about your example you should use

{% if node.field_foo.entity.title.value|render|trim %}
                {{ node.field_foo.entity.title.value|render }}
            {% endif %}

I hope this works for you.

Ivan Berezhnov’s picture

Issue tags: +CSKyiv18
larowlan’s picture

Category: Bug report » Support request
Status: Active » Fixed

Item #3has the fix, adding |trim

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.

Shifali Baghel’s picture

It worked. Great!!!

Cayenne’s picture

Works for me too. Seems like an awkward fix, but it works for me.

chefigueroa’s picture

#3 worked. Thanks!