1

I have a section with a matrix field that collects multiple notes for each entry, each marked by the date the note is entered. Conceptually, the data is organized within the entries as:

Entry A
     Jan 1     Note
     Mar 1     Note

Entry B
     Feb 1     Note
     Apr 1     Note

I would like to extract all the notes from all the entries, and then display the collected information sorted by the dates the notes were entered, as in:

Jan 1    Note     Entry A
Feb 1    Note     Entry B
Mar 1    Note     Entry A
Apr 1    Note     Entry B

Is this possible in Craft? I'm aware of the SuperSorter plugin, but am not sure whether what I am explaining is possible. If it is, I'm unclear about the syntax required to construct the query properly.

Thanks

1 Answer 1

3

Yes, you can do that with matrix block queries. Instead of going through entries to get the matrix blocks, you can query matrix blocks independently with a custom sort order.

{% set notesByDate = craft.matrixBlocks()
    .type('note')
    .orderBy('note_date ASC')
    .all()
%}

Replace note with the handle of the matrix block type of your notes and note_date with the handle of the date field.

This will give you a list of matrix blocks. From the matrix blocks, you can get the owner entry using MatrixBlock::getOwner():

{% for note in notesByDate %}
    Date: {{ note.date | date('medium') }}
    Note: {{ note.note }}
    Entry: {{ note.getOwner().title }}
{% endfor %}

Limiting matrix blocks to specific section

You can't limit a matrix block query to a specific section directly since they don't belong to a section. Matrix blocks are owned by entries and those entries belong to a section. So you need to limit the matrix query to matrix blocks that are owned by the entries in that section:

{% set entriesInSection = craft.entries().section('myCustomSection').ids() %}
{% set notesByDateInCustomSection = craft.matrixBlocks()
    .type('note')
    .orderBy('note_date ASC')
    .ownerId(entriesInSection)
    .all()
%}
4
  • 1
    Brilliant - just what I needed. Thanks!
    – Ed Hebert
    Jun 29, 2022 at 14:28
  • While this got me 99% of the way there, I use this particular matrix block in several sections of the site. I want to filter the output to results from a particular section. I found that Matrix Blocks to not accept a .section() parameter. Any way to filter these matrixBlock results by section?
    – Ed Hebert
    Jun 29, 2022 at 15:36
  • @EdHebert I've added an example for limiting the query to a specific section!
    – MoritzLost
    Jun 30, 2022 at 7:40
  • 1
    thanks so much - worked!
    – Ed Hebert
    Jun 30, 2022 at 13:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.