Counting DataList in template

Silverstripe Version: 4.1.2

Question: How can I read the total number of items in a DataList?

I’ve created a custom function to grab some event entries and feed them back. As this is used in several places, I’ve included 2 variables. For context, there are two types of events which are “General” and “Interview”.

This is my function in the controller:

    public function getEvents($count = 5, $type = "General")
        $List   = CalendarEntry::get()
                        "Date:GreaterThanOrEqual"   => date('Y-m-d'),
                        "Type"                      => $type
                    ->Sort("Date, Time");

        return $List;

This successfully returns a list of events which I can read through a loop. Then in my template, I have:

In my template, I then use:

<% if $getEvents(4, Interview).TotalItems > 0 %>
     <% loop $getEvents(4, Interview) %>
          $Title <br>
     <% end_loop %>
<% else %>
    No interviews found
<% end_if %>

The result, I would expect, should be at least 1 event title, or “no interviews found”. At the moment, I get neither, nor do I get any errors.

Any pointers appreciated. As always, if there’s something that can be improved on the little function above, I’m all ears (or eyes in this case?)

You should be able to just use the following:

<% if $getEvents(4, Interview) %>
  <% loop $getEvents(4, Interview) %>
  <% end_loop %>
<% else %>
  <p>Sorry, no interviews found</p>
<% end_if %>

As simple as that :slight_smile: . I think I was just overcomplicating it!


1 Like

You might also consider a private property cache and assign to it on the first call (based on your params, so possibly an array) and use that to provide the data in the second call, otherwise the DB will be called twice for the request.