Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to implement a search filter form with Symfony2
    text
    copied!<p>I have a list of items to display on a page, with a search form above it to filter these items, like in any usual backend. The problem is that I don't know how to add the search criteria to an existing query with joins... Here's what I have: </p> <p>I use a specific method on the repository associated to the entity to add joins on the query (in order to avoid many queries). The controller looks like this:</p> <pre><code>class ModelController extends Controller { public function indexAction(Request $request) { // ... $em = $this-&gt;getDoctrine()-&gt;getManager(); $query = $em-&gt;getRepository('AcmeDemoBundle:Item')-&gt;getList(); } } </code></pre> <p>The <code>getList</code> method on the repository looks like this:</p> <pre><code>use Doctrine\ORM\EntityRepository; // ... class ItemRepository extends EntityRepository { public function getList() { $queryBuilder = $this -&gt;createQueryBuilder('i') -&gt;innerJoin('i.brand', 'b'); return $queryBuilder-&gt;getQuery(); } } </code></pre> <p>I created a <code>ItemSearchType</code> form object with several fields to search for items.</p> <p>How can I easily add the search criteria from the data provided in the search form to display the filtered items?</p> <p>This is what's in my controller concerning the search form:</p> <pre><code>class ModelController extends Controller { public function indexAction(Request $request) { // ... if ($request-&gt;getMethod() === 'POST') { $searchForm-&gt;bindRequest($request); if ($searchForm-&gt;isValid()) { $searchCriteria = $searchForm-&gt;getData(); // Do something with this data! ...but I don't know how } } } </code></pre> <p>Thanks!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload