6

I would like to allow registered users to submit entries to sections. The documentation didn't mention how to get the values and labels of dropdown / checkbox / multiselect fields to show them as options on the submitting page. I can't use the entry variable because the entry is not saved yet.

10

You can get info about your fields using craft.fields.getFieldByHandle(). That will include a settings property, which will be an array of the field type’s settings.

The actual settings available will differ depending on the field type, but Dropdown, Checkboxes, and Multi-select fields all have the same one: options. So in each of their cases, here’s how you would loop through the options:

{% set field = craft.fields.getFieldByHandle('myFieldHandle') %}
{% for opt in field.settings.options %}
    <label>
        <input name="fields[myFieldHandle][]" type="checkbox" value="{{ opt.value }}">
        {{ opt.label }}
    </label>
{% endfor %}
| improve this answer | |
  • I tried to figure this out a while ago but couldn't. I don't think field.settings is mentioned anywhere in the docs, unless I'm mistaken? It's quite handy when you want to grab generic field options rather than setting up user or entry. – Rob Feb 17 '16 at 18:29
  • Why do you have the <input>'s name parameter set to fields[myFieldHandle][] instead of just myFieldHandle[] - or even more automated, field.handle[]? – Sandwich Apr 27 '16 at 19:53
  • 2
    @Sandwich Because Craft expects all of the custom field POST values to be tucked away in a fields namespace. – Brandon Kelly Apr 27 '16 at 19:55
  • Ok, so would the automated ideal be fields[{{ field.handle }}][]? – Sandwich Apr 27 '16 at 20:00
  • @Sandwich Yeah you could do fields[{{ field.handle }}][] if you want. Seems overkill in this example since field was literally fetched by its handle, so not much need to make it dynamic here. – Brandon Kelly Apr 28 '16 at 3:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy