0

The display of a dropdown without optgroups is defined:

{% set field = craft.app.fields.getFieldByHandle('<FieldHandle>') %}

<select name="fields[<FieldHandle>]">
    {% for option in field.options %}

        {% set selected = entry is defined
            ? entry.<FieldHandle>.value == option.value
            : option.default %}

        <option value="{{ option.value }}"
                {% if selected %}selected{% endif %}>
            {{ option.label }}
        </option>
    {% endfor %}
</select>

The following error occurs:

Key "default" for array with keys "optgroup" does not exist.
2

This would work for both with or without optgroup (replace aDropdown with your fieldname):

{% set field = craft.app.fields.getFieldByHandle('aDropdown') %}

{# If we have optgroups in this field, set a counter to 0 else return false #}

{% set optgroupCount = field.optgroups ? 0 : false %}
<select name="fields[aDropdown]">
    {% for option in field.options %}

        {% if option.optgroup is not defined %}
            {# This is a regular option #}
            {% set selected = entry is defined ? entry.aDropdown.value == option.value : option.default %}
            <option value="{{ option.value }}" {% if selected %}selected{% endif %}>
                {{ option.label }}
            </option>
        {% else %}
            {# This is an optgroup #}
            {# Check if we should close a group before opening a new one.#}
            {{ optgroupCount > 0 ? '</optgroup>' }}
            <optgroup label="{{ option.optgroup }}">
            {% set optgroupCount = optgroupCount + 1 %}
        {% endif %}

    {% endfor %}
    {# If we had optgroups better close the last one #}
    {{ optgroupCount ? '</optgroup>' }}
</select>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for?Browse other questions tagged or ask your own question.