3

I am new in Craft, and will be happy if I can get help with this task. I have a tab that contains only multiselect fields. What I want to do, is to get all selected values for all multiselects field in this tab. I find this answer to get all field from a tab, but I can't get the selected values for the entry. Here is my code:

{% for tab in entry.getFieldLayout().getTabs() %}
  {% if tab.name == 'Spec' %}
    <ul>
      <li>{{ tab.name }}
        <ul>
          {% for field in tab.getFields() %}
            <li>{{ field.getField().name }}</li>
          {% endfor %}
        </ul>
      </li>
    </ul>
  {% endif %}
{% endfor %}

1 Answer 1

2

You can loop through all of the selected values of a multi-select field like this:

{% for value in entry.myFieldHandle %}
  <li>{{ value }}</li>
{% endfor %}

(See the Multi-select field docs for other examples.)

The easiest way to loop through all of your multi-select fields’ values would be to manually merge all of their values into a new array:

{% set values = entry.fieldHandleOne
    |merge([entry.fieldHandleTwo])
    |merge([entry.fieldHandleThree]) %}

{% for value in values %}
    {{ value }}
{% endfor %}

If you really don’t want to hardcode the field handles in your template, then you can go the getFieldLayout() route. That field.getField() function will give you the actual FieldModel that represents the field. You can use its handle property to access the field’s selected values on your entry:

{% set values = [] %}

{% for tab in entry.getFieldLayout().getTabs() %}
  {% if tab.name == 'Spec' %}
    {% for field in tab.getFields() %}
      {% set handle = field.getField().handle %}
      {% set fieldValues = entry.getFieldValue(handle) %}
      {% set values = values|merge([fieldValues]) %}
    {% endfor %}
  {% endif %}
{% endfor %}

{% for value in values %}
  {% for selected in value %}
    <li>{{ selected}}</li>
  {% endfor %}
{% endfor %}
4
  • Hi, thank you for response. I have been trying your solution, but I get this error The merge filter only works with arrays or hashes; array and object given.. Oct 20, 2015 at 8:46
  • I made a quick search and solve the problem adding square brackets {% set values = values|merge([fieldValues]) %} and another loop to print the values {% for value in values %} {% for selected in value %} <li>{{ selected }}</li> {% endfor %} {% endfor %}. If There is a better solution I will be glad to know it. Thanks for help. Oct 20, 2015 at 8:58
  • @IvayloPetrov Whoops, sorry about that! Just fixed the code. Oct 20, 2015 at 20:12
  • Don`t worry, we all are humans ;) You miss to fix last code example :) I fixed it :) Oct 21, 2015 at 6:53

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.