Doctrine query builder in Symfony 2 - thehazels Doctrine query builder in Symfony 2 - thehazelsthehazels

Doctrine query builder in Symfony 2

I’ve found many different opinions on the best way to use Doctrine query builder in Symfony 2. I needed to return a query joining four tables. I hit many errors before finding a working solution.

The requirement was to use a custom query to build a select list in a form. Symfony’s documentation recommends using the repository for this.

First thing to bear in the mind is that most repository functions return a result generated with createQuery. This time I needed a function returning a query builder object.

I also had two parameters to pass. These can be passed to the form in the $options array (remembering to add them to  the form’s setDefaults). My setParameters were ignored until I applyed them to the where clauses.

The most difficult error was a ‘500 End of script output’. The query needs to return the entity object, and I has only specified the field.

The form:

public function buildForm(FormBuilderInterface $builder, array $options)
      $customer = $options['customer']; 
      $type = $options['type'];
        ->add('description', 'entity', array(
            'class' => 'MyBundle:TableA',
            'query_builder' => function( EntityRepository $er ) use ( $customer, $type ) {
               return $er->findCatTypesQuery( $customer, $type );
public function setDefaultOptions(OptionsResolverInterface $resolver)
        'data_class' => 'MyBundle\Entity\TableA',
        'customer' => 1,
        'type' => '',

TableA’s repository:

$em = $this->getEntityManager();
$query = $em->createQueryBuilder( )
     ->from( 'MyBundle:TableA', a')
     ->innerJoin('b.item', 'b')
     ->innerJoin('c.item', 'c')
     ->innerJoin('d.item', 'd')
     ->where('a.type = :type')->setParameter('type', $type)
     ->andWhere('b.customer = :customer')->setParameter('customer', $customer)
return $query;

About Antonia Whitaker

An administrative, sales and marketing background has given me an understanding of what users want from their website. I do not confuse issues with technical jargon and I listen to what people want.

26. March 2014 by Antonia Whitaker
Categories: Symfony | Tags: | Leave a comment

Leave a Reply

Required fields are marked *