Clive Portman: code

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')
    .region(':notempty:')
    .hideThisSchoolFromTheSchoolsPage(':empty')
    .order('title')
%}
{% 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 %}
</ul>
{% endfor %}

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