2

I'm building a calendar functionality and I need to get entries by month, but they cannot restricted by year (as, for example, the calendar might have entries that fall on both Jan 2017 and Jan 2018).

At the moment, I'm doing a for loop and incrementing to get the next 5 years:

{% set categoryParam = craft.request.getParam('month') %}

{% if categoryParam %}
  {% set allDates = [] %}

  {% for i in 0..5 %}
    {% set year = now|date('Y') + loop.index0 %}
    {% set combinedDate = '1970-' ~ categoryParam ~ '-01' %}

    {% set startDate = year ~ '-' ~ combinedDate|date('m') ~ '-01' %}
    {% set dayCount = startDate|date('t') %}
    {% set endDate  = year ~ '-' ~ combinedDate|date('m') ~ '-' ~ dayCount %}

    {% set courseDates = craft.entries({ section: 'courseDates', limit: null }).order('courseStartDate').courseStartDate('and','>= ' ~ startDate, '<=' ~ endDate) %}

    {% for courseDate in courseDates %}
      {% if courseDate not in allDates %}
        {% set allDates = allDates|merge([courseDate]) %}
      {% endif %}
    {% endfor %}
  {% endfor %}

{% else %}
  {% set allDates = craft.entries({ section: 'courseDates', limit: null }).order('courseStartDate').courseStartDate('and','>= ' ~ now) %}
{% endif %}

I'm just wondering if there is a better way of doing this that doesn't rely on the year?

3

I think a better way would be to add a Preparse field to your Course Dates’ field layout that stores only the month.

https://github.com/aelvan/Preparse-Field-Craft

The code for the preparsedMonth field.

{{ entry.courseStartDate|date('m') }}

With that in place you can drastically simplify your template code and reduce database queries.

{% set categoryParam = craft.request.getParam('month') %}

{% set allDates = craft.entries({
    section: 'courseDates',
    courseStartDate: '>= ' ~ now|date('c'),
    preparsedMonth: categoryParam ? '%02d'|format(categoryParam) : null,
    order: 'courseStartDate',
    limit: null,
}) %}
| improve this answer | |

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.