Lucas Lobosque
Lucas Lobosque

Reputation: 399

API Platform - always apply filter on custom operation

I have a custom collection operation on my entity (/api/posts/active), and I want to always apply a few filtering conditions to it:

  1. Fetch only those with active = true;
  2. Fetch only those with onlineUntil > now();

How do I do this ONLY for this specific collectionOperation, and not all of them?

Also, how do I implement these filters by default, without dependencies on query strings like /posts/:id/active?active=true.

I have read the documentation regarding filtering but I'm really confused as they never mention filtering only a specific operation or applying the filter by default, without the query strings.

Upvotes: 1

Views: 1809

Answers (2)

antograssiot
antograssiot

Reputation: 171

That's the typical use case for a custom extension (https://api-platform.com/docs/core/extensions)

Upvotes: 1

Vasiliy Toporov
Vasiliy Toporov

Reputation: 875

I think that filters are not needed here. You could achieve your goal with custom operation (see custom operation section in the docs) and switch off receiving for it. And then, inside the __invoke method get collection of active posts with qustom query from the PostRepository, which could be retrieved there by injecting in the custom operation constructor:

public function __construct(EntityManagerInterface $em)
{
    $this->em = $em;
}

Upvotes: 1

Related Questions