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?
1 Answer
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.
- 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 doesdatemean in.field_dw_date.date?pglatz– pglatz2022-05-14 17:42:54 +00:00Commented May 14, 2022 at 17:42 - 1See drupal.stackexchange.com/questions/252333/…4uk4– 4uk42022-05-14 23:18:46 +00:00Commented May 14, 2022 at 23:18