2

I have a entity

Product:
  name # string
  country # entity
  categories #entity many-many

I have a form for that entity

ProductType: name categories

now i need filter categories by country but i dont wanna show a country parameter when i build the form I do

//...
$entity = new Entity\Product();
$entity->setCountry($this->getUser()->getProfile()->getCountry());
$form = $this->createForm(new Form\ProductType(), $entity);

return array('form' => $form->createView());

i want filter the categories by country in the ProductType class, how can achieve this?.

How i can pass $country value to query builder?

//...
->add('categories', 'entity', array(
  'class' => 'MyBundle:Category',
  'query_builder' => function(EntityRepository $er) {
    return $er->createQueryBulder('c');
  }
)
4

1 回答 1

7

您正在寻找options可以传递给表单类的数组。将此添加到您的 FormType:

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'country' => null
    ));
}

然后FormType像这样调用:

$this->createForm(new Form\ProductType(), $entity, array(
    'country' => $country
));

并像这样访问$country您的buildForm方法:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $country = $options['country'];

从那里开始,您可以构建自己的queryBuilder以仅选择您需要的产品。

编辑: 要访问$countryqueryBuilder 中的变量,您应该使用use语句。它看起来像这样:

->add('categories', 'entity', array(
   'class' => 'MyBundle:Category',
   'query_builder' => function (EntityRepository $er) use($country) {
       // here you can use the $country variable in your anonymous function.
       return $er->createQueryBuilder('c');
       }
    )
)
于 2013-06-13T21:48:17.443 回答