我有以下实体关系:
所以,在我的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?那么每个地址都有相应的县来查找城市?
任何帮助将不胜感激。谢谢!
答案 0 :(得分:8)
在symfony3中:
$builder->add('example', CollectionType::class, array(
'entry_type' => ExampleType::class,
'entry_options' => array(
'my_custom_option' => true),
));
答案 1 :(得分:3)
在AddressType中使用构造函数,它适用于我..
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,
))
;
}
地址类型:
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);
},
}
答案 2 :(得分:2)
我认为你可以使用集合类型的'options'选项。如果你想在其他地方重用表单,那么它比使用构造函数更好。
Symfony表格参考:Collection Type
但请记住在setDefaultOptions
方法中定义变量。 (两种形式都必须有)