【问题标题】:pass parameters from entity to query_builder将参数从实体传递到 query_builder
【发布时间】:2013-06-13 21:35:52
【问题描述】:

我有一个实体

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

我有那个实体的表格

产品类型: 姓名 类别

现在我需要按国家/地区过滤类别,但我不想在构建表单时显示国家/地区参数

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

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

我想在 ProductType 类中按国家/地区过滤类别,如何实现?

如何将 $country 值传递给查询构建器?

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

【问题讨论】:

  • 我已经更新了我的答案。

标签: php forms symfony symfony-forms


【解决方案1】:

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

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

然后像这样调用FormType:

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

并在您的buildForm 方法中访问$country,如下所示:

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

从那里您可以建立自己的queryBuilder 以仅选择您需要的产品。

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

->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');
       }
    )
)

【讨论】:

  • 我构建了我的解决方案,但使用包含实体事件 $options['country'] 的 $options['data']。谢谢你的想法
猜你喜欢
  • 2015-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-15
  • 2017-08-28
  • 2014-03-03
相关资源
最近更新 更多