Sort custom fields by descending date with sort_by_key filter


Sorry if it is a silly question but I am trying to sort a custom field collection by descending date but can’t find out how to do this with the sort_by_key filter.

Could someone please tell me how I can do this?

Concerned fields in my song.yaml file

      ordering@: 2
      type: fieldset
      title: Enregistrements
      help: Ajouter les enregistrements faits pendant les répétitions
      icon: microphone
      collapsed: true
      collapsible: true
          name: recordingItem
          type: list
          style: vertical
              type: text
              label: Titre
              type: date
              label: Date
              type: file
              label: Fichier audio
              destination: 'self@'
              multiple: false
              filesize: 30MB
              accept: ['.mp3', '.wma', '.wav']

The code in my songs.html.twig file:

{% set recordingItems = page.header.recordingItem %}

      {% for recordingItem in recordingItems|slice(2,last)|sort_by_key('recordingDate') %}
      <div class="prise grid-x">
        <div class="cell">
          <p class="h3 float-left">{{ recordingItem.prise }}</p>
          <p class="label float-right"><i class="material-icons">event</i> {{ recordingItem.recordingDate }}</p>
        <div class="cell">
          <audio controls preload="none">
            <source src="{{ recordingItem.recordFile|first.path }}" type="audio/mp3">
            Votre navigateur ne supporte pas le format audio.
      {% endfor %}

The result I have on the front office:

The result I would like to have:

I think I found a solution with the Twig reverse filter :grinning:

So I did this:

{% for recordingItem in recordingItems|reverse|slice(0,3) %}

… and I can display my last 3 items as following:

Note: I added more items since I posted this question


1 Like