Score:1

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?

Score:3
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:

field--node--field-my-paragraph-field.html.twig:

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

See the Twig 2.x docs (available for Drupal >=9): https://twig.symfony.com/doc/2.x/filters/sort.html


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'].field_dw_date.date.gettimestamp() <=> b.content['#paragraph'].field_dw_date.date.gettimestamp()) %}`. It isn't working though, I don't understand how the fields are dereferenced. What does `date` mean in `.field_dw_date.date` ?
4uk4 avatar
cn flag
See https://drupal.stackexchange.com/questions/252333/how-to-get-formatted-date-string-from-a-datetimeitem-object
pglatz avatar
in flag
Good to know, thanks.
mangohost

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.