1

I have a form that contains a static select input of U.S. States:

<select id="state" name="state" class="form-control">
<option value=""> Select </option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
....
</select>

I have the validation figured out on my form, and also have my text inputs getting repopulated if there are any validation errors. I am curious about the best method to repopulate my select input.

I can access the value that was entered via:

{% set state = craft.request.getParam('state') %}

Which will give me "AL" or "AK" (whichever was chosen). This is fine, but because my list is static, do I now need to have logic on every option?

For example, something like this...

<option value="AL" {% if state == AL %}selected="selected" {%endif%}>Alabama</option>

Or, is there a better way all together?

FWIW, here is how I am repopulating my text inputs:

value="{% if model is defined %}{{ model.name }}{% endif %}

Thank you!

3

No, I don't think there's a better way, you need to add that conditional to each select option. But what you could do is to refactor a bit and move that logic to a Twig macro.

{% macro stateOption(id, name, selectedId) %}
    <option value="{{ id }}"{{ id == selectedId ? ' selected="selected"' }}>{{ name }}</option>
{% endmacro %}
{% import _self as forms %}

{% set selectedId = craft.request.getParam('state') %}

{% set states = {
    'AL': 'Alabama',
    'AK': 'Alaska',
    'AZ': 'Arizona',
} %}

<select id="state" name="state">
    <option value="">Select</option>

    {# Go through states and use the custom macro to generate the select options #}
    {% for id, name in states %}
        {{ forms.stateOption(id, name, selectedId) }}
    {% endfor %}
</select>
  • Ah - this is exactly the shove I needed. (Obviously) I'm new to twig development, and was searching the docs for all the wrong things it seems. I figured I would have to do it 50x times, (yuck) but the macro is the way to roll. Thank you very much!! – Damon Mar 24 '15 at 15:05

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.