Symfony2将值传递给集合表单类型 [英] Symfony2 passing values to collection form type

查看:59
本文介绍了Symfony2将值传递给集合表单类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下实体关系:

  • 客户有一对多的地址
  • 地址具有多对一县和多对一城市
  • 一个县有一对多的城市.

所以,在我的CustomerType中,我有

So, in my CustomerType, I have

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ...
        ->add('addresss', 'collection', array(
            'label' => 'customer.address',
            'type' => new AddressType(),
            'allow_add' => true,
            'allow_delete' => true,
            'by_reference' => false,
        ))
    ;
}

在我的AddressType中,我有

And in my AddressType, I have

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ...
        ->add('city', 'entity', array(
            'class' => 'MyCustomerBundle:City',
            'query_builder' => function(CityRepository $cr) use ($options) {
                return $cr->getCityQB($options['county']);
            },
            'property' => 'city',
            'empty_value' => '',
        ))
    ;
}

我的目标是仅显示对应县的城市集.我可以将值从$ options获取到CustomerType中,但是如何将这些值传递给AddressType?这样每个地址都可以得到其对应的县来查找城市?

My goal is to only display the set of cities for their corresponding county. I can get the values into CustomerType from $options but how can I pass down the values to AddressType? So that each address gets its corresponding county to look up the cities?

任何帮助将不胜感激.谢谢!

Any help would be appreciated. Thanks!

推荐答案

在AddressType中使用构造函数,它对我有用.

Use the constructor in AddressType, its works for me..

CustomerType:

CustomerType:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ...
        ->add('addresss', 'collection', array(
            'label' => 'customer.address',
            'type' => new AddressType($your_variable),
            'allow_add' => true,
            'allow_delete' => true,
            'by_reference' => false,
        ))
    ;
}

AddressType:

AddressType:

private $your_variable;

public function __construct($variable)
{
    $this->your_variable= $variable;
}
...
public function buildForm(FormBuilderInterface $builder, array $options){
    $your_variable = $this->your_variable;
    'query_builder' => function(CityRepository $cr) use ($your_variable) {
        return $cr->getCityQB($your_variable);
    },
}

这篇关于Symfony2将值传递给集合表单类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆