2

I would like to loop through all the fields of a field layout tab form the current entry.

This is working fine to get the field name and value:

{% for fieldLayoutField in entry.getFieldLayout().getFields() if fieldLayoutField.tabId == 50 %}
    {% set field = craft.app.fields.getFieldById(fieldLayoutField.id) %}
    Field name: {{ field.name }}
    Field value: entry[field.handle]
{% endfor %}

But I need to go a step further, by checking the field type, and then handle something different depending of the type.

Example:

{% if field.type == 'dropdown' %}
    <select>
        {% for option in field.options %}
            <option value="{{ option.value }}">
                {{ option.label }}
            </option>
        {% endfor %}
    </select>
{% endif %}

As {{ field.type }} and {{ entry[field.handle].type }} aren't defined, I can't guess properly when this is, for example, a Plain Text field or a Dropdown field.

I could guess some fields type, by some checks like bellow, but it sounds very dirty:

  • field.columnType returns text if a Plain Text field.
  • field.options | length returns true if a Dropdown field.

For some others, like the Lightswitch field, I don't know exactly how to guess the type properly.

1 Answer 1

5

You can use the className function

{% switch className(field) %}
    {% case 'craft\\fields\\PlainText' %}
    {% case 'craft\\fields\\Dropdown' %}
0

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.