Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.x] Add hook to query on entries listing #10479

Merged
merged 6 commits into from
Jul 18, 2024
Merged

Conversation

duncanmcclean
Copy link
Member

@duncanmcclean duncanmcclean commented Jul 18, 2024

This pull request adds a hook that allows developers to modify the query used to return entries for the entries listing table.

Here's a super simple example of how you might use it to only display a user's posts on the news collection, which could go hand in hand with a policy:

use Statamic\Hooks\CP\EntriesIndexQuery;

EntriesIndexQuery::hook('query', function ($payload, $next) {
    if ($payload->collection === 'news') {
        $query->where('author', User::current()->id());
    }

    return $next($payload);
});

Closes statamic/ideas#591.

@ryanmitchell
Copy link
Contributor

I think we'd need some way of knowing what collection this was for, as you'd want to apply it conditionally, not on every index query.

Maybe the hook could be renamed per collection. eg pages:index-query, or alternatively it could pass a DTO but thats a bit yuck.

@jasonvarga
Copy link
Member

jasonvarga commented Jul 18, 2024

I've made a generic Payload DTO with some magic so it's a bit easier to work with. Pass an array, it uses the DTO and you can access the keys with property access.

You can now use

$this->runHooksWith('name', ['array' => 'of', 'payload' => 'stuff'])

then your hooks can be like:

Whatever::hook('name', function ($payload, $next) {
  // getters
  $payload->array;
  $payload->stuff;

  // setters
  $payload->stuff = 'changed';

  return $next($payload);
});

The way you'd actually set up this would be something like this:

use Statamic\Hooks\CP\EntriesIndexQuery;

EntriesIndexQuery::hook('query', function ($payload, $next) {
    if ($payload->collection === 'blog') {
        $payload->query->where('foo', 'bar');
    }

    return $next($payload);
});

@jasonvarga jasonvarga changed the title [5.x] Add index-query hook to entries listing [5.x] Add hook to query on entries listing Jul 18, 2024
@jasonvarga jasonvarga merged commit a96a6a1 into 5.x Jul 18, 2024
19 checks passed
@jasonvarga jasonvarga deleted the entries-index-query-hook branch July 18, 2024 18:48
duncanmcclean added a commit to statamic/docs that referenced this pull request Jul 31, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Ability to modify the query used in listings (entries, etc)
3 participants