Search code examples
phpsymfonydoctrine-ormapi-platform.com

api-platform filter out the soft deleted items


I have setup the soft delete for my Store entity by using softdelete.

This is my filter setup in the doctrine.yml:

doctrine:
    # ...
    orm:
        # ...
        filters:
            softdeleteable:
                class: Gedmo\SoftDeleteable\Filter\SoftDeleteableFilter
                enabled: true

So when I hit e.g. the URL /stores only the active stores are returned, but if I change the config to enabled: false it will give me all the results including deleted items, which is correct.

Now what I want to achieve is pass a query parameter from front-end like /stores?deleted=1 and then I want to get all the data, if no deleted=1 found only the active items


Solution

  • Why not create an event listener that uses the Request object and Doctrine's entity manager, and disables this filter? Something like this:

    class FilterListener implements EventSubscriberInterface
    {
        private $entityManager;
    
        public function __construct(EntityManagerInterface $entityManager)
        {
            $this->entityManager = $entityManager;
        }
    
        public static function getSubscribedEvents(): array
        {
            return [
                RequestEvent::class => 'onKernelRequest',
            ];
        }
    
        public function onKernelRequest(RequestEvent $event)
        {
            if (!$event->isMasterRequest()) {
                return;
            }
    
            $request = $event->getRequest();
            if ($request->query->getBoolean('deleted')) {
                $this->entityManager->getFilters()->disable('softdeleteable');
            }
        }
    }