TransWikia.com

Looping on the User Field added to Entry

Craft CMS Asked by Dan Lee on January 15, 2021

I am fetching the fields of an entry in a block but can not draw through a user field named as eventHost.

I get error ‘Variable "name" does not exist.’ What is wrong with my loop?

{% set webinar = block.webinar.all() %}
{% if webinar is not empty %}


{% for entry in webinar %}

        {% set url = entry.url %}
        {% set title = entry.title %}
        {% set desc = entry.previewDescription %}
        {% set img = entry.previewImage.one() %}

        {% for expert in entry.eventHost %}
            {% set name = expert.name %}
            {% set avatar = expert.avatar %}
            {% set job = expert.personJobTitle %}
            {% if expert.linkedInProfile %}
                {% set linkedin = expert.linkedInProfile.url %}
            {% endif %}
        {% endfor %}

{{ title }}

{{ name }}
{{ job }}

{% endfor %}

{% endif %}

One Answer

You are setting variables within the scope of the for loop – they only exist there. You can fix this by setting up empty variables before the loop, like:

{% set webinar = block.webinar.all() %}
{% if webinar is not empty %}
    {% for entry in webinar %}

        {# Setup empty variables #}

        {% set name = null %}
        {% set avatar = null %}
        {% set job = null %}
        {% set linkedin = null %}

        {% set url = entry.url %}
        {% set title = entry.title %}
        {% set desc = entry.previewDescription %}
        {% set img = entry.previewImage.one() %}   

        {% for expert in entry.eventHost %}
            {% set name = expert.name %}
            {% set avatar = expert.avatar %}
            {% set job = expert.personJobTitle %}
            {% if expert.linkedInProfile %}
                {% set linkedin = expert.linkedInProfile.url %}
            {% endif %}
        {% endfor %}

        {{ title }}
        {{ name }}
        {{ job }}

    {% endfor %}
{% endif %}

Or in one line, for neatness:

{% set name, avatar, job, linkedin = null, null, null, null %}

This one has got me many times ;)

Answered by dmatthams on January 15, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP