1

I have a page that displays musicians grouped by their musical instrument. I am outputting them grouped by instrument, but I have been asked to sort the instrument groups by a custom order specified by the client. Not alphabetical, but a specified order. How should I handle this? I was using .orderBy(‘instrument asc’) in the query to get them in alphabetical order. Would I be creating an array and then assigning keys to them for the order I want and then order by the numerical keys or something? I haven’t been able to figure it out yet. Code snippet below:

  {% set relatedMusicians=craft.entries.section('bios’)
     .relatedTo(entry)
     .orderBy('instrument asc')
     .with(['bioPhoto'])
     .all() 
  %}
  • What field type do you use for instrument? – Oli Jan 12 at 6:59
  • Plain text; I thought of a dropdown but there are lots of possible instruments and there might be more added down the road, so plain text is what I did. – M Smith Jan 12 at 14:37
  • I'd recommend another field type if at all possible. Categories or even related entries (structure) will give you far more flexibility than a plain text field. Are you still in a position to change that? – Oli Jan 12 at 15:30
  • I could conceivably change the field type, yes. That being said, please note that each musical group’s leader wants their instrumental groups in a different order, so the clarinets might be at the top of one group’s list and the bottom of another’s... so setting up a structure might not do the trick...? Or maybe there is a way? I’m quite open to suggestions... I saw this old post about a SuperSort plugin and I wonder if it could be a possible start... craftcms.stackexchange.com/questions/11050/… – M Smith Jan 12 at 19:13
1

I would like to thank Michael Rog for supplying an answer at this similar question about SuperSort:

Sorting an array of entries according to a fixed list/array of items

The code that lets me sort by instrument in any order I want:

  {% set relatedMusicians = craft.entries.section('bios').relatedTo(entry)
  .with(['bioPhoto'])
  .all() 
  %}

        {% set sortAsList = [
          "violin",
          "viola",
          "cello",
         ] %}

{% set sortedMusicians= relatedMusicians
| supersort('customOrderSortAs', as='{instrument}', comp=sortAsList) %}

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.