0

Maybe Craft 4 is playing games with me but im stuck on this problem:

  • linkedEntry is an entry field which is limited to 1 entry.

This outputs the section handle correctly

 {% set linkedEntry = category.linkedPage %}
 {% dd(linkedEntry.section.handle) %}

This tells me that the section() function is called without an parameter

{% set linkedEntry = category.linkedPage %}
{% if linkedEntry.section.handle === 'exampleHandle' %}

And this tells me that i cant call the attribute section on null

{% if category.linkedPage.section.handle === 'exampleHandle' %}

Am i missing something thats new in Craft 4?

Greetings

3 Answers 3

2

If the linkedEntry field is empty, then category.linkedPage.one() will evaluate to null, so you should always add a condition to check that a value exists before calling a method on it.

{% set linkedEntry = category.linkedPage.one() %}

{# Explicit syntax. #}
{% if linkedEntry is not null %}
    {% set handle = linkedEntry.section.handle %}
{% endif %}

{# Alternative, simpler syntax. #}
{% if linkedEntry %}
    {% set handle = linkedEntry.section.handle %}
{% endif %}
1

You haven't executed your element query: https://craftcms.com/docs/4.x/element-queries.html#executing-element-queries

(If you attempted to do this in Craft 3 it would have given you a slapped wrist by logging a deprecation warning in the control panel, but would have executed the element query for you anyway). Craft 4 is more strict about ensuring that you execute your element queries yourself. It's an important concept to understand, because otherwise you can blindly end up putting element queries inside loops, which is terrible for performance.

{% set linkedEntry = category.linkedPage.one() %}
0

You both are correct.

I started experimenting with and without .one(). But the real problem was that the person i was trying to help did not fill out all the required fields and thus the errors were thrown and the behaviour threw me off...

Sorry for this and thank you for all your help and tips

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.