Can paragraph fields in a node be sorted?

in flag

I have a node content type with a paragraph field with multiple values. The paragraph has a date and a text field. When I display the node, I'd like to sort the paragraph values by date. I've tried doing this in twig with the sort filter to no avail. Can this be done somehow, maybe with preprocessing the field?

cn flag

This should be no problem sorting the field items in preprocessing the field, but since Drupal 9 this can also be done in Twig.

For example:


{% set items = items|sort((a, b) => a.content['#paragraph'] <=> b.content['#paragraph'] %}

See the Twig 2.x docs (available for Drupal >=9):

If the .date property doesn't work it's a different field type. Try the generic .value property:

{% set items = items|sort((a, b) => a.content['#paragraph'].field_foo.value <=> b.content['#paragraph'].field_foo.value) %}

This also applies to the Timestamp field type. Not often used for configured fields, most times for base fields like Created or Changed.

pglatz avatar
in flag
Thanks - I was trying something similar, but couldn't get it to work. The date field in my paragraph type is called `field_dw_date`, so my sort looks like this: `% set items = items|sort((a, b) => a.content['#paragraph'] <=> b.content['#paragraph'] %}`. It isn't working though, I don't understand how the fields are dereferenced. What does `date` mean in `` ?
4uk4 avatar
cn flag
pglatz avatar
in flag
Good to know, thanks.

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.