Optional Entity Field Type Query Parameter

I want to build the Entity field type in Symfony 2 and pass the parameter to the query designer for a list of filters for 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 the $ id of this function inside formMapper?

+6
source share
2 answers

You can use closing PHP 5.3. Most languages ​​with closure do this automatically, but PHP requires that you explicitly list this.

 'query_builder' => function (EntityRepository $er) use ($id) { return $er ->createQueryBuilder('sc') ->where('sc.article_category = :id') ->orderBy('sc.name', 'ASC') ->setParameter('id', $id); } 
+8
source

A good way is to use an array of parameters when creating the form, so pass id in the array and then in the form do:

 public function buildForm(FormBuilderInterface $builder, array $options) { $id = $options['id']; $builder ->add('foo', 'entity', array( 'class' => 'Foo', 'query_builder' => function (EntityRepository $er) use ($id) { return $er->findByBar($id); } )) ; } 
+1
source

Source: https://habr.com/ru/post/907022/


All Articles