1

I'm outputting an element criteria model in a Craft 2 plugin of some entries in a channel. I noticed that when I fetch the entries the standard template way

{% set entries = craft.entries.section('channelHandle') %}

I am then able to do something like the following to refine the number of entries with the lightswitch turned on:

{% set refinedEntries = entries.customLightswitchField(1)|length %}

However, when I fetch my entries in my plugin, output them into the template, then try refining it as above:

// plugin
$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = 'channelHandle';
$entries = $criteria->find();
return $entries;

// template
{% set entries = craft.myPlugin.fetch() %}
{% set refinedEntries = entries.customLightswitchField(1)|length %}

...I then get an Array to string conversion PHP notice. I'm also not able to use things like .first() like I normally would.

Is this expected behavior? Am I missing something when returning an element criteria model through a plugin?

Ryan
  • 1,952
  • 1
  • 15
  • 24

1 Answers1

2

Of course this is the expected behavior because you don't return an ElementCriteriaModel from your plugin.

You do return $criteria->find(); so you'll return an array of entries but not an ElementCriteriaModel if you want to return the object instead of the entries you have to do return $criteria.

As soon as you use the find() method Craft builds a query based on your ElementCriteriaModel, executes it and returns you an array of elements or null.

Robin Schambach
  • 19,713
  • 1
  • 19
  • 44