繁体   English   中英

Symfony2将值传递给集合表单类型

[英]Symfony2 passing values to collection form type

我有以下实体关系:

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

所以,在我的CustomerType中,我有

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中,我有

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? 那么每个地址都有相应的县来查找城市?

任何帮助,将不胜感激。 谢谢!

在symfony3中:

$builder->add('example', CollectionType::class, array(
    'entry_type'   => ExampleType::class,
    'entry_options'  => array(
        'my_custom_option'  => true),
));

使用AddressType中的构造函数 ,它适用于我..

客户类型:

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

地址类型:

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

我想你可以使用集合类型的'options'选项。 它比使用构造函数更好,以防您想在其他地方重用该表单。

Symfony表格参考: 集合类型

但请记住在setDefaultOptions方法中定义变量。 (两种形式都必须有)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM