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 ?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With