php - 将参数从实体传递到 query_builder

标签 php forms symfony symfony-forms

我有一个实体

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

最佳答案

您正在寻找可以传递给表单类的 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');
       }
    )
)

关于php - 将参数从实体传递到 query_builder,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17097513/

相关文章:

php - 像 artisan 一样为我自己的自定义 php 框架创建自定义

php - 将选择列表传递给 php 页面

javascript - Laravel 中的 Html 表单

forms - Angularjs 检查表单中的部分是否有效

asp.net - jQuery POST 不改变 IsPostback 变量

c# - 在执行期间创建 Windows 窗体控件

php - Composer 更新 => fatal error : Out of memory

php - Symfony 表单不保存具有 ManyToMany 关系的实体

php - 读取excel数据并按以下格式插入

php - Laravel Chained Select 无法加载资源 : the server responded with a status of 500