Is there a way to return an empty DataList on purpose?

Silverstripe Version: 4 or 3, this subject is not about a specific version. If a solution can be found in either version, I would be glad.


Sometimes when doing filtering on DataLists, there are exceptional cases where I would like to make the DataList empty on purpose.

This is what I have used so far, but it’s not efficient as it performs an unnecessary database query:

$empty_data_list = DataList::create('MyDataObject')->where('FALSE');

For example, I might want to show a list of DataObjects to logged in users only, but if a user is not logged in, she should see nothing in the list. I know this could be handled in a different way by checking the login status in the template that is used to output the list, but I would still like to know a general solution to this subject.

Thanks! :slight_smile:

I’ve encountered this problem before too, in situations where you want to be consistent and predictable with what you’re returning. I did a similar thing to you, from memory I think I did ->filter('ID', 0). If there’s a more efficient approach I’m interested to hear as well.

If you just need an empty list and nothing else, and you don’t want to refine that list, why not simply return an empty ArrayList? Both implement the SS_List interface and are quite interchangeable e.g. in templates.

I’ve considered this too, but like @JonoM, I would like a method’s return type to be as predictable as possible. ArrayList and DataList share a lot of common functions but there still is a possibility to end up using a method on the returned (empty) list that is only available if the list is a DataList. And if it happens to be an ArrayList instead of a DataList, it will crash the application.

I’m just trying to avoid possible errors in edge cases. And I also like to keep method return types and descriptions as simple as possible: no need to describe why a method usually returns a DataList and sometimes an ArrayList. :slight_smile: