0

I have a users form, which they can select their occupations. They can choose multiple values from a multi-select input.

Occupations are categories that are related to users profile.

Here in this code, i can get the values and submit witout any problem,but i cannot show as selected when user returns to form. They should see thier previous selections.

{% set categories = craft.categories.group('occupation').all() %}  
<input type="hidden" name="fields[occupation][]" value="">
<select multiple name="fields[occupation][]" class="selectpicker" >

{% for category in categories %}        
  {% set selected = currentUser.occupation.all()  %}    
  <option value="{{ category.id }}" {% if category.id == selected  %} selected{% endif %} > {{ category.title }} </option>
{% endfor %}

How can i access to selected arrays id value?

2

When you do currentUser.occupation.all() your selected variable is an objet so your conditional {% if category.id == selected %} will never pass as you are checking if category.id equals an object.

For this to work, first get the ids of the currentUser occupations:

{% set selected = currentUser.occupation.ids() %}

Which would return an array of ids (key/value pairs) then you compare doing:

{% if category.id in selected|values %}

So in full:

    <select multiple name="fields[occupation][]" class="selectpicker" >
        {% for category in categories %}        
        {% set selected = currentUser.occupation.ids() %}
          <option value="{{ category.id }}" {% if category.id in selected|values %} selected{% endif %} > {{ category.title }} </option>
        {% endfor %}
    </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.