How to implement a search filter form using Symfony2

I have a list of elements to display on a page with a search form above it to filter these elements, as in any regular backend. The problem is that I don’t know how to add search criteria to an existing query with joins ... Here is what I have:

I use the specific method in the repository associated with the entity to add joins to the request (to avoid many requests). The controller looks like this:

class ModelController extends Controller
{
    public function indexAction(Request $request)
    {
        // ...
        $em = $this->getDoctrine()->getManager();
        $query = $em->getRepository('AcmeDemoBundle:Item')->getList();
    }
}

The method getListin the repository is as follows:

use Doctrine\ORM\EntityRepository;

// ...

class ItemRepository extends EntityRepository
{
    public function getList()
    {
        $queryBuilder = $this
            ->createQueryBuilder('i')
            ->innerJoin('i.brand', 'b');

        return $queryBuilder->getQuery();
    }
}

I created a form object ItemSearchTypewith several fields to search for elements.

How can I easily add search criteria from the data presented in the search form to display the filtered items?

This is what is in my controller regarding the search form:

class ModelController extends Controller
{
    public function indexAction(Request $request)
    {

        // ...
        if ($request->getMethod() === 'POST') {
           $searchForm->bindRequest($request);

           if ($searchForm->isValid()) {
               $searchCriteria = $searchForm->getData();

              // Do something with this data! ...but I don't know how
           }
     }
}

!

+5
2

:

public function getListBy($criteria)
{
    $qb = $this->createQueryBuilder('i');

    $qb->innerJoin('i.brand', 'b');

    foreach ($criteria as $field => $value) {
        if (!$this->getClassMetadata()->hasField($field)) {
            // Make sure we only use existing fields (avoid any injection)
            continue;
        }

        $qb ->andWhere($qb->expr()->eq('i.'.$field, ':i_'.$field))
            ->setParameter('i_'.$field, $value);
    }

    return $qb->getQuery()->getResult();
}
+8

, LexikFormFilterBundle filterTypes QueryBuilder, TypeGuesser, , .

Composer. .

README, github: P

/**
 * Creates a Filter form to search for Entities.
 *
 * @param AbstractType|string $formType The `generate:doctrine:form` generated Type or its FQCN.
 *
 * @return \Symfony\Component\Form\Form The filter Form
 */
private function createFilterForm($formType)
{
    $adapter = $this->get('dd_form.form_adapter');
    $form = $adapter->adaptForm(
        $formType,
        $this->generateUrl('document_search'),
        array('fieldToRemove1', 'fieldToRemove2')
    );
    return $form;
}

SF >= 2.8

+2

All Articles