Determining the Number of Selected Items in a Multi-select Field
Problem
You want to determine the number of selected items in a multi-select field.
Solution
Determining the number of selected items in a multi-select field is simple, but perhaps a little confusing at first.
You may be accustomed to using the length
Twig filter to retrieve the number of items in an array, and assume that this will work just fine with the multi-select field:
{# This won't work #}
{{ entry.myMultiSelectField|length }}
In reality, this will always return 1
, because the multi-select field value is an object, not an array.
The correct way to retrieve the number of selected items is as follows:
{{ entry.myMultiSelectField.count }}
Submitted by Stephen Lewis on 1st February, 2017