Take the 2-minute tour ×
Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. It's 100% free, no registration required.

I have a template which displays a table of all the bookings on the website. The booking channel entries consist of two fields: a related user, and a related event, 1:1. There's a drop-down list of all the events at the top of the template which lists all of the events on the site. When a user clicks on an event title, the table updates to only show bookings related to that event (done by applying a class to all rows, and hiding every row which doesn't have the same class as the chosen event slug). The filter code looks like this:

<form class="event-filter">
    <label for="filter">Filter event: </label>
    <select id="filter" name="filter">
        {% for event in craft.entries.section('event') %}
        <option value="i{{event.id}}">{{event.title}}</option>
        {% endfor %}
    </select>
</form>

The bookings table displays all the events using something like this:

{% set bookings = craft.entries.section('booking').order('postDate desc') %}

Is there a way for my filter form to list my events, and display the number of bookings for each event? So it would say, for example:

  • First event (3 bookings)
  • Second event (8 bookings)

I'm sure it must be possible using relations, but I can't work out the syntax.

share|improve this question

1 Answer 1

up vote 3 down vote accepted

Try something like this:

<form class="event-filter">
    <label for="filter">Filter event: </label>
    <select id="filter" name="filter">
        {% for event in craft.entries.section('event') %}    
            {% set numEventBookings = craft.entries.section('booking').relatedTo(event).total() %}
            <option value="i{{event.id}}">{{event.title}} ({{numEventBookings}} bookings)</option>
        {% endfor %}
    </select>
</form>

But it'll generate one database query pr event, so it might be a bit inefficient, depending on your setup.

share|improve this answer
    
This works, thank you :) That page is already pretty heft for database queries I think.. It's already querying the database for every booking multiple times... I'm not good at templating optimisation! If anyone has any ideas on optimising it further, comments welcome. Thanks aelvan. –  Daryl Knight Aug 30 at 17:13
    
If you already are getting all the bookings and have them in the DOM of the page, I'd consider just doing the counting in the frontend with javascript/jquery. Just make a reference on each booking entry to the event, do some query'ing and insert the count in the appropriate places. Client side work is cheap. :) –  André Elvan Aug 30 at 19:59

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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