Trying to show selected categories in a multi select form input 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() %}  
&lt;input type="hidden" name="fields[occupation][]" value=""&gt;
&lt;select multiple name="fields[occupation][]" class="selectpicker" &gt;

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




How can i access to selected arrays id value?
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:

    &lt;select multiple name="fields[occupation][]" class="selectpicker" &gt;
        {% for category in categories %}        
        {% set selected = currentUser.occupation.ids() %}
          &lt;option value="{{ category.id }}" {% if category.id in selected|values %} selected{% endif %} &gt; {{ category.title }} &lt;/option&gt;
        {% endfor %}
    &lt;/select&gt;