1

I have an entries field 'physicians'. I want to output the selections from that field and sort them by category (also named 'physicians') - with the category heading above each category group.

I can't figure out if I should just output the category list and filter the result by the field or if I should output the entries field and then sort them by category. I'm trying the latter right now but not sure of how to get the categories to work.

{% set phyGroup = craft.categories.group('physicians') %}
{% set phyList = craft.entries.relatedTo('physicians').order('lastName asc') %}

{% for physicians in phyGroup %}
   <h3>{{ category }}</h3>
   {% for entry in phyList %}
      {{ entry.lastName }} ...
   {% endfor %}
{% endfor %}
  • Am I right in assuming that you have a Categories field added to the field layout of the entries that you pick with your physicians Entries field? What’s the handle of that field? – carlcs Jul 6 '17 at 13:59
  • Yes, on the entries that I pick from there is a categories field named 'specialityCat'. – David Jul 6 '17 at 15:27
4
+50

It’s not totally clear from your question where you’re building the relation to the categories, but I have a feeling that this is the solution you’re looking for.

{% set groupParam = '{ object.categoriesFieldHandle.first() ? object.categoriesFieldHandle.first().title : "No categories" }' %}
{% for groupTitle, entriesInGroup in entry.entriesFieldHandle|group(groupParam) %}
    {{ groupTitle }}

    {% for entry in entriesInGroup %}
        {{ entry.title }}
    {% endfor %}
{% endfor %}
  • I am trying to show the entries selected in the entries field but sort them in category groups. The entries I'm pulling from have a category field called 'specialityCat'. Would I need to use this in conjunction with the 2 'set' parameters I have above? Not getting this to work yet but I have this: {% for group, entriesInGroup in entry.physicians|group('specialityCat') %} {{ group.title }} {% for entry in entriesInGroup %} <p>{{ entry.title }}</p> {% endfor %} {% endfor %} – David Jul 6 '17 at 15:53
  • @David I updated the code example, should work now. – carlcs Jul 6 '17 at 21:03

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.