Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity field type custom query parameter

I want to build a Entity field type in Symfony 2 and pass a parameter to query builder for filter list of related objects:

$formMapper
            ->add('article_subcategories', 'entity',
                    array(
                         'label' => 'Podkategorie',
                         'multiple' => true,
                         'expanded' => true,
                         'read_only' => true,
                         'class' => 'FachowoArticleBundle:ArticleSubcategory',
                         'query_builder' => function (EntityRepository $er)
                         {
                             return $er
                                     ->createQueryBuilder('sc')
                                      ->where('sc.article_category = :id')
                                      ->orderBy('sc.name', 'ASC')
                                      ->setParameter('id', $id);
                         }
                    ));

How can i pass $id to this function inside formMapper ?

like image 220
Pawel Avatar asked Jan 27 '12 13:01

Pawel


1 Answers

You can use PHP 5.3's closures. Most languages with closures do this automatically, but PHP requires that you specify the list explicitly.

'query_builder' => function (EntityRepository $er) use ($id)
   {
      return $er
        ->createQueryBuilder('sc')
        ->where('sc.article_category = :id')
        ->orderBy('sc.name', 'ASC')
        ->setParameter('id', $id);
    }
like image 129
Louis-Philippe Huberdeau Avatar answered Sep 28 '22 01:09

Louis-Philippe Huberdeau