Grouping Entries by First Letter of Last Name
A tutorial on how to group entries by the first letter of a field value in Craft CMS. In this example we'll be ordering a list of book authors by their last name with a header for each letter of the alphabet with results.
I'm working on a site where there are a large number of authors with books listed on the sites. The goal is to list all the authors alphabetically by last name with a header above each letter.
The end result will look like this:
In order to do this we need to use the group filter. We do this by first getting all the entries. The channel I have is called authors
and has fields for firstName
and lastName
.
After getting the entries, group them with the | group
filter and then finally loop through all the entries outputting entries grouped alphabetically by first letter of last name.
{# get all the entries #}
{% set allEntries = craft.entries.section('authors').orderBy('lastName asc, firstName asc').all() %}
{#
// group all entries by first letter of last name
// https://docs.craftcms.com/v3/dev/filters.html#group
#}
{% set allEntriesByGroup = allEntries | group('lastName[:1]') %}
{# loop through the entries #}
{% for firstLetter, entriesInGroup in allEntriesByGroup %}
{# display the Letter #}
<h2>{{ firstLetter }}</h2>
{# display the authors for this letter #}
<ul>
{% for entry in entriesInGroup %}
<li>
<a href="{{ entry.url }}">{{ entry.title }}</a>
</li>
{% endfor %}
</ul>
{% endfor %}