Skip to content

Use Behaviors to create custom query scopes for element queries? #13636

Closed Answered by brandonkelly
aaronbushnell asked this question in Q&A
Discussion options

You must be logged in to vote

Yep, this is definitely a valid use case for behaviors.

Your event handler could be simplified – no need to ensure it’s an EntryQuery as you’re already registering a class-level event for EntryQuery instances, and you can set your behavior on $event->behaviors rather than manually attaching it.

use craft\elements\db\UserQuery;
use craft\events\DefineBehaviorsEvent;
use yii\base\Event;

Event::on(
    UserQuery::class,
    UserQuery::EVENT_DEFINE_BEHAVIORS,
    function(DefineBehaviorsEvent $event) {
        $event->behaviors[] = QueryBehavior::class;
    }
);

And as @wsydney76 said, you should be using andWhere() within your behavior, so it doesn’t override any conditions already set on t…

Replies: 2 comments 2 replies

Comment options

You must be logged in to vote
1 reply
@aaronbushnell
Comment options

Comment options

You must be logged in to vote
1 reply
@aaronbushnell
Comment options

Answer selected by brandonkelly
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants