Skip to main content
2 of 4
added 489 characters in body
Damon
  • 4.7k
  • 1
  • 20
  • 36

How can I repopulate my dropdown on a front-end form?

I am allowing guest registrations - everything is working fine. I am hung up on getting my drop down menu to repopulate/hold its value if there are any errors while submitting.

I have a states field in the CP which is a dropdown.

Within my twig template I have this:

{#
 # Get all of the states.
 #
 #}
 {% set states = craft.fields.getFieldByHandle('states').getFieldType.options %}
 {% if states|length %}
     <div class="form-group">
         <label for="state">State</label>
         <select id="state" name="fields[address][state]" class="form-control">
             <option value="">Select</option>
             {% for option in states %}
                 <option val="{{ option.value }}"
                     {%- if account is defined and option.value in account.address.state %} selected {% endif -%}>
                     {{ option.label }}
                 </option>
             {% endfor %}
         </select>
     </div>
 {% endif %}
 {% if account is defined %}
     {{ errorList(account.getErrors('state')) }}
 {% endif %}

I am using SmartMap to capture my address hence the name of fields[address][state].

Just doing this:

{%- if account is defined %} selected {% endif -%}

Gets the last option selected, so I know account is getting defined, its something in my and part.

All of my data is getting captured correctly, I just can't see past the obvious here I guess.

SOLUTION

Thanks to @carlcs I found that the value of my state field was getting saved as the label. I'm not sure if thats a function of SmartMap, or something else I might have done.

Here is what I ended up with:

...
{% for option in states %}
    <option val="{{ option.value }}"
        {%- if account is defined and option.label in account.address.state %} selected {% endif -%}>
        {{ option.label }}
    </option>
{% endfor %}
Damon
  • 4.7k
  • 1
  • 20
  • 36