3

I am getting all entries from a section like this:

// get the parent entry.
{% set author = craft.entries.section('mySection').authorId(currentUser.id).first() %}

// get the child entries from the parent.
{% set entires = craft.entries({
    'section': 'mySection',
    'level': 2,
    'descendantOf': author.id
 })%}

// myDate is a dateTime filed (yyyy-mm-dd)

{% for year, entry in entries|group('myDate') %}
            <h4>{{ year|date('Y') }}</h4>
            <ul>
                {% for entry in entries %}
                    {% if attempt.myDate|date('Y') == year|date('Y') %}
                        <li>{{ entry.myDate }} > {{ entry.type.name }} - {{ entry.foo }}</li>
                    {% endif %}
                {% endfor %}
            </ul>
        {% endfor %}

What I have is close, however, it's outputting multiple years. For example,

2016
  [entry]

2016
  [entry]

2015
  [entry]

 ...

I'm trying to group all of the child entries by year. For example, if I have 3 entires with the same year (2016) I am trying to show:

2016
  [entry]
  [entry]
  [entry]

2015
  [entry]

2014
  [entry]
  [entry]

...

Thank you for any suggestions!

4

You're currently grouping on the myDate field, which essentially creates a new array index for each date (e.g. 2016-01-01) which is why you're getting your current output.

To group by year, this should do the trick:

{% for year, entries in entries|group('myDate.year') %}
    <h4>{{ year }}</h4>
    <ul>
        {% for entry in entries %}
            ...
        {% endfor %}
    </ul>
{% endfor %}
  • Ah - yes! I was thinking about the myDate field as a whole, not get just the year from it. Thank you! – Damon Sep 10 '16 at 13:23
1

I think that the official Craft CMS documentation provides an answer to your question really clearly: https://craftcms.com/support/entry-archive

For example,

{% set childEntires = craft.entries({
    'section': 'mySection',
    'level': 2,
    'descendantOf': author.id
})%}

{% for date, entries in childEntires | group("myDate|date('Y')") %}
    <h2>{{ date }}</h2>
    <ul>
        {% for entry in entries %}
            <li>{{ entry.myDate | Y }} > {{ entry.type.name }} - {{ entry.foo }}</li>
        {% endfor %}
    </ul>
{% endfor %}
  • 1
    Would you mind expanding this answer to include some of the information found at that URL? Link-only answers are frowned upon, as they may change or break in the future. – Lindsey D Mar 10 '17 at 18:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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