【发布时间】:2012-11-13 09:34:52
【问题描述】:
我有两个实体,A 和 B。A 与 B 具有一对多关系。
我使用collection 字段类型在A 表单中嵌入了五个B 表单。为此,我在AController 中创建了 5 个 A-B 关系。我想做的是使用每个B 实体的字段在表单集合中构建其标签。
所以,我有以下代码:
//AController
$a = new A();
//Followinf returns an array of 5 B entities
$bs = $this->getDoctrine->getEntityManager()->getRepository('MyBundle:B')->findBy(array(
'field' => 'value',
));
foreach ($bs as $b) {
$a->addB($b);
}
$form = $this->createForm(new AType(), $a);
return array(
'a' => $a,
'form' => $form->createView(),
);
//AType
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('a_field')
->add('another_field')
->add('bs', 'collection', array(
'type' => new BType(),
'options' => array(
'label' => 'i want to configure it depending on current B data',
)
))
;
}
我找到了这个相关的话题:
Symfony form - Access Entity inside child entry Type in a CollectionType
但请注意,这是不同的,因为它访问子表单中的数据。我想从父表单访问子数据并将其用于集合中的每个子标签。
我知道我可以使用 $builder->getData()->getBs(); 访问子数据,但我不知道以后如何为每个子表单使用它。
我也知道我可以在视图中执行此操作,循环遍历实体并使用循环索引手动呈现每个集合元素,但我想在表单中执行此操作。
非常感谢。
【问题讨论】:
标签: symfony symfony-2.1