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:
...
<option value="">Select</option>
{% 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 %}
Alternatively, here is how I was able to repopulate a "normal" drop-down (not address/SmartMap):
...
<option value="">Select</option>
{% for option in myField %}
<option val="{{ option.value }}"
{%- if account is defined and option.label in account.myField.label %} selected {% endif -%}>
{{ option.label }}
</option>
{% endfor %}
I think it's also worth noting that by setting myField
as a required field in the CP, I needed to hard-code the <option value="">Select</option>
in the template rather than putting it as a field value. When I had it as a field value, I (think) Craft was accepting that as a selected value and I was not getting the error message.