1. cliveportman
  2. /code
  3. /group-entries-by-contents-of-dropdown-field-within-craft-cms

Group entries by contents of dropdown field within Craft CMS

The region field is a Craft CMS dropdown <select> containing a list of regions like Central, South East, etc. I wanted to filter out the entries without a region and group them by region so I could list the schools under region headings.

{% set allSchools = craft.entries.section('schools')
{% set allSchoolsGroupedByRegion = allSchools | group('region.label') %}
{% for region, schoolsInRegion in allSchoolsGroupedByRegion %}
 <ul class="region">
    <h4>{{ region }}</h4>
    {% for school in schoolsInRegion %}
        <li>{{ school.title }}</li>
    {% endfor %}
{% endfor %}

There's one caveat - to order the regions you need to use the Supersort plugin, or something similar.