How to enforce and hide filters on a Sonata’s list view
Sonata provides you with a robust and easy to implement interface administration for your Symfony projects.
We have been using and loving it on my projects for 19 weeks now. Every day we are amazed with the time we save thanks to Sonata.
However, there are some features that our client wants that are missing. One of them is the possibility to hide filters.
Imagine you want your users to see a pre-filtered Sonata list and do not display the filters.
In our case we receive applications. Each application has a status and a at certain point we have a button “View pending application”. This button of course is supposed to list only the “pending” applications and we don’t want the users to be able to change this filter.
This solution is really straight-forward and easy to implement, give us 5 minutes and 30 lines of code!
Note: this tutorial is written for Symfony 2.8 and Sonata 2.3. Let me know in the comments if you tested it on other configurations.
The easy solution : createQuery
When you search for a solution online you easily find examples of people using the createQuery function of Sonata:
In your admin class:
You now have great filters you can enable and disable at will. Last issue: when you edit an element and then come back to the list your filters have disappeared.
The fix for that is to use Sonata’s persistent parameters: it’s a really handy function that will had your filters to all the Sonata generated links.
Add that to your admin class: