0

I am new to craftcms and searching did not get any answer. I have 2 fields setup navUrl (type entries) and customUrl (url) and I have a section called mainMenu with these fields. I have then added the entries for this section with each navUrl pointing to the structure entries (home, about etc).

For example my site has

Home Blog about contact

In template I am can access the title, customUrl but unable to access navUrl which has the url for home page, about page etc.

How do I access the url which is selected in navUrl? doing a dump actually shows the field navUrl as null!

Getting the URI of an Entries field in a Structure with no URLs - solution mentioned doesnt work

1 Answer 1

1

The entries field will give you its value in the form of an EntryQuery, which you can execute to get the actual entry. I'm guessing your navUrl field allows only one entry? In this case, it's best to execute the query with .one(), which will return either the entry selected in the field or null if no entry is selected.

{% set navEntries = craft.entries().section('mainMenu').all() %}

{% for entry in navEntries %}
    {% set linkedEntry = entry.navUrl.one() %}
    {% set targetUrl = linkedEntry ? linkedEntry.getUrl() : entry.customUrl %}
{% endfor %}

You can reduce that to a handy one-liner with the null coalescing operator:

{% set navEntries = craft.entries().section('mainMenu').all() %}

{% for entry in navEntries %}
    {% set targetUrl = entry.navUrl.one().getUrl() ?? entry.customUrl %}
%}
{% endfor %}

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.