1

I have a multi-select for users to sign up for newsletters. When they edit their profile they need to be able to see which newsletters they are already signed up for. I have the code to output the entire options list or just the ones that they have selected but I haven't figured a way to add the selected attribute to the ones the user has selected.

{% set newsletters = craft.fields.getFieldByHandle('newsletters') %}
<select multiple>
    {% for opt in newsletters.settings.options %}
        <option value="{{ opt.value }}" >{{ opt.label }}</option>
    {% endfor %}
</select>

The "for opt in newsletters.settings.options" can be changed to "for opt in newsletters.settings" to show just the ones the user has already selected.

  • Guessing this should work but form reloads page and doesn't save {% set newsletters = craft.fields.getFieldByHandle('newsletters') %} <select name="fields[newsletters]" id="newsletters" multiple> {% for opt in newsletters.settings.options %} {% set created = false %} {% for opti in newsletters.settings %} {% if opti.value == opt.value %} <option value="{{ opt.value }}" selected="selected">{{ opt.label }}</option> {% set created = true %} {% endif %} {% endfor %} {% if created == false %} <option value="{{ opt.value }}">{{ opt.label }}</option> {% endif %} {% endfor %} </select> – Indigo Viking Nov 15 '17 at 2:39
  • Do you want to know get to know how to save your changes into the database? – Robin Schambach Nov 15 '17 at 10:58
  • Yes, I need it to save the changes and also have a way to add selected or some attribute if the user had previously selected that option. – Indigo Viking Nov 15 '17 at 13:10
3

Solved!

{% for letter in currentUser.newsletters.options %}
    <input type="checkbox" value="{{ letter.value }}" name="{{ letter.value }}" id="{{ letter.value }}"
        {% if letter.selected == true %}checked="checked" {% endif %}/>
    <label for ="{{ letter.value }}">{{ letter.label }}</label>
{% endfor %}

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.