Skip to content
Grav 2.0 is officially stable. Read the announcement →

Community guidelines

Please keep discussions civil and on-topic. Repeated violations may lead to a temporary ban.

Themes & Styling

Sort custom fields by descending date with sort_by_key filter

Solved by Benjamin View solution

Started by Benjamin 8 years ago · 1 replies · 837 views
8 years ago

Hello,

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

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

The code in my songs.html.twig file:

TWIG
{% 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>
        <div class="cell">
          <audio controls preload="none">
            <source src="{{ recordingItem.recordFile|first.path }}" type="audio/mp3">
            Votre navigateur ne supporte pas le format audio.
          </audio>
        </div>
      </div>
      {% endfor %}

The result I have on the front office:

image|690x385

The result I would like to have:

image|690x386

8 years ago Solution

I think I found a solution with the Twig reverse filter 😀

So I did this:

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

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

image|690x387
Note: I added more items since I posted this question

🙌

👍 1

Suggested topics

Topic Participants Replies Views Activity
Themes & Styling · by Pedro M, 2 months ago
4 195 2 months ago
Themes & Styling · by Ian, 2 months ago
3 91 2 months ago
Themes & Styling · by Norbert, 2 years ago
11 451 3 months ago
Themes & Styling · by Lukáš Findeis, 3 months ago
0 45 3 months ago
Themes & Styling · by Sebadamus, 4 months ago
5 125 3 months ago