1

I need to write a conditional that determines if events actually exist in a calendar. I only want to display an option in the the select dropdown IF the calendar has events:

{% set calendars = craft.calendar.calendars({
    limit: 100,
    order: "name",
    sort: "asc"
}) %}

{% set events = craft.calendar.events({
    calendarId: calendar.id
}) %}

{% for calendar in calendars %}

    {# determine what the URL should look like based on the current URL structure #}

    {% if segment1 == '' %}
        {% set urlPart = "month/calendar/" ~ calendar.handle ~ "/" ~ month.date.format('Y/m') ~ "#1" %}
    {% elseif segment3 is not empty and segment4 is not empty %}
        {% set urlPart = "month/calendar/" ~ calendar.handle ~ "/" ~ segment4 ~ "/" ~ segment5 ~ "#2" %}
    {% else %}
        {% set urlPart = "month/calendar/" ~ calendar.handle ~ "/" ~ segment2 ~ "/" ~ segment3 ~ "#3" %}
    {% endif %}

    {# I need a conditional here that outputs an option only IF there are events in the calendar #}

    {% if events %}
        <option value="{{ siteUrl }}cal/{{ urlPart }}"{% if segment3 == calendar.handle %} selected="selected"{% endif %}>
            {{ calendar.name }} - {{ calendar.event.occurrenceCount }}
        </option>
    {% endif %}

{% endfor %}

UPDATE: I expanded this out so you can see everything. Unfortunately, this is still outputting all calendars even if the calendar has no events.

  • Of course you have to search the events for each calendar.... so you have to search the events inside your loop. Your calendar variable is not even defined at this point – Robin Schambach Mar 23 '18 at 14:34
  • I apologize, but I'm a newbie to Craft (migrating from EE). Perhaps you could help me with a code example? – Vaughn D. Taylor Mar 23 '18 at 14:38
  • This has nothing to do with a certain CMS/Framework it's just about basic code logic, I updated my answer – Robin Schambach Mar 23 '18 at 14:44
3

Looking at the docs you can search for events for a certain calander by including the id or the handle in your query.

{% set calendars = craft.calendar.calendars({
    limit: 100,
    order: "name",
    sort: "asc"
}) %}

{% for calendar in calendars %}
    {% set events = craft.calendar.events({
        calendarId: calendar.id
    }) %}

    {% if events|length %}
        // there are events
    {% else %}
        // calendar has no events
    {% endif %}
{% endif %}

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.