Is a custom field type and making use of modifyElementsQuery the only way to add my own craft.entries element criteria model attribute to modify the elements query?

What if I do not want to add a new field to each entry type I want to use my attribute with? The field would be a hidden pseudo field anyways, as I'm only working with other fields' data.

My current solution is passing the element criteria model with all other params set to craft()->elements->buildElementsQuery() using a template variable. It works, yes, but I would really like to avoid this (pagination not possible and some other disadvantages).

  • Have you thought about using a template hook? If you think that might be a viable solution, I can write up an official answer. :)
    – Lindsey D
    Commented Oct 13, 2015 at 16:48
  • Thanks Lindsey, but I need this to be a bit more flexible than a template hook would make this for the user of the plugin.
    – carlcs
    Commented Oct 13, 2015 at 18:18
  • Makes sense... and that's exactly why I didn't spend time writing a full answer already. :)
    – Lindsey D
    Commented Oct 13, 2015 at 18:21

1 Answer 1


Currently, yes, the only way to modify an element query (when it’s not your own element type) is to do it with a custom field type, from its modifyElementsQuery() function.


As of Craft 2.5, plugins can listen for the elements.onBeforeBuildElementsQuery and elements.onBuildElementsQuery events to make changes to the query (or prevent it from getting executed).

craft()->on('elements.buildElementsQuery', function(Event $event) {
    /** @var ElementCriteriaModel $criteria */
    $criteria = $event->params['criteria'];

    /** @var DbCommand $query */
    $query = $event->params['query'];

    if ($criteria->myCustomParamName) {
        $query->andWhere( //...
  • I'm trying to use your suggested buildElementsQuery event, but when I use $criteria->myCustomParamName it's not passing myCustomParamName to my plugin and I'm getting an error in the logfiles Property "Craft\ElementCriteriaModel.myCustomParamName" is not defined. I'm trying to use a custom parameter from the elementCriteria in my templates. What am I missing here?
    – ctigelaar
    Commented Feb 8, 2016 at 16:42
  • @Christiaan What version of Craft are you running? Commented Feb 8, 2016 at 21:51
  • @Brandon I'm using Craft 2.5.2761
    – ctigelaar
    Commented Feb 9, 2016 at 6:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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