symfony2 form querybuilder with parameters
Asked Answered
A

2

23

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.

Abbottson answered 12/12, 2012 at 19:16 Comment(0)
H
43

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

Hildegaard answered 12/12, 2012 at 19:45 Comment(2)
your link is died !Tango
Can i Pass EnityManger Query instead of QueryBuider.? Does it works .?Furunculosis
O
15

I recently ran across almost the same problem. Only difference was the 'query_builder' option has to be set inside 'setDefaultOptions'. Basicly the form is created like this:

$builder->add('field', 'query_type', array('id' => 1));

The 'query_type' class looks like this:

class QueryType extends AbstractType
{
     public function setDefaultOptions(OptionsResolverInterface $options)
     {
              $resolver->setRequired(array('id'));

              $resolver->setNormalizers(array(
                  'query_builder' => function (Options $options, $configs) {
                          return function (EntityRepository $er) use ( $options ) {
                              return $er->getSomething( $options['id'] );

                       };
                  },
              ));
     }
}

I use the setNormalizers function to access my $options array and from there on i can call the querybuilder with parameters.

Hope this is useful for someone!

Orestes answered 19/9, 2013 at 11:41 Comment(1)
Good solution if you need options in your anonymous function, when defining default options.Wiebmer

© 2022 - 2024 — McMap. All rights reserved.