1

Looking at a means to perform subqueries against certain searches in the back-end of the Craft CMS eg for searches against particular sections within Admin > Entries.

Looking into this it seems like the SearchEvent event might be best, and specifically EVENT_BEFORE_SEARCH. Was hoping can pass an array of specific elementIds into the event to tighten up the number of results returned but that doesn't seem to be working.

Example code:

  Event::on(
    Search::class,
    Search::EVENT_BEFORE_SEARCH,
    function (SearchEvent $event) {
      $sender = $event->sender;
      $sectionId = $elementQuery->sectionId;
      if ($sectionId == [4]) {
        $event->setElementIds($elementIdsArray); // eg [123,455], etc
      }

  });

However this is ignore and the usual search takes place. Can anyone advise the best way to limit back-end searches to certain elementIds?

Cheers,

Cole

1 Answer 1

1

There are some errors in your code – maybe those just snuck in when you posted the code here, but right now the hook can't work correctly:

  • $elementQuery is undefined – did you mean $event->elementQuery?
  • $elementIdsArray is also not defined.
  • Make sure you're importing the correct Search class (craft\services\Search).

Besides that, I don't think the SearchEvent::setElementIds function is intended to set element IDs to be used for the query. If you look at the source code, the SearchEvent created for this hook is not saved as a variable and the method doesn't check if you've set any element IDs on the event:

// Fire a 'beforeSearch' event
if ($this->hasEventHandlers(self::EVENT_BEFORE_SEARCH)) {
    $this->trigger(self::EVENT_BEFORE_SEARCH, new SearchEvent([
        'elementQuery' => $elementQuery,
        'query' => $searchQuery,
        'siteId' => $siteId,
    ]));
}

If you set the element IDs on the element query itself, the hook starts working correctly:

use craft\services\Search;
use craft\events\SearchEvent;

Event::on(
    Search::class,
    Search::EVENT_BEFORE_SEARCH,
    function (SearchEvent $event) {
        $elementQuery = $event->elementQuery;
        $elementQuery->id([123, 455]);
    }
);

Now the last thing to check is if your condition is failing for some reason. A simple way to test this is to put a Craft::dd statement in there. Then go to Admin -> Entries in the backend, open the devtools in your browser and execute a search. Look for the search request executed by JavaScript, open it and look at the Response tab. There you can see the dumped value.

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.