symfony2 form querybuilder with parameters

Mitchel Verschoof picture Mitchel Verschoof · Dec 12, 2012 · Viewed 44k times · Source

I want to put my entity in the function of the query builder:

->add( 'weeks', 'entity', array(
    'class' => 'MV\CaravanBundle\Entity\CaravanRow',
    'property' => 'line',
    'query_builder' => function(EntityRepository $er ) use ( $caravan ) {
        return $er->createQueryBuilder('w')
                  ->orderBy('w.dateFrom', 'ASC')
                  ->where('w.caravan = ?', $caravan )
                  ->andWhere('w.visible = 1')
                  ->andWhere('w.booked = 0');
}

but get the message:

Expression of type 'Entity\Name' not allowed in this context

So what is the (best) way to give the querybuilder information.

Answer

Squazic picture Squazic · Dec 12, 2012

You should set the parameter separately like so:

->add( 'weeks', 'entity', array(
    'class' => 'MV\CaravanBundle\Entity\CaravanRow',
    'property' => 'line',
    'query_builder' => function(EntityRepository $er ) use ( $caravan ) {
        return $er->createQueryBuilder('w')
                  ->orderBy('w.dateFrom', 'ASC')
                  ->where('w.caravan = ?1')
                  ->andWhere('w.visible = 1')
                  ->andWhere('w.booked = 0')
                  ->setParameter(1, $caravan);
}

You can either use an integer or string, but the syntax is slightly different for each. See the docs