我有两个实体,A 和 B。A 与 B 具有一对多的关系。
我使用collection
字段类型在 A 表单中嵌入了五个 B 表单。为此,我在我的AController
. 我想做的是使用每个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 表单 - 在 CollectionType 中的子条目类型中访问实体
但请注意这是不同的,因为它访问子表单中的数据。我想从父表单访问子数据并将其用于集合中的每个子标签。
我知道我可以使用访问子数据,$builder->getData()->getBs();
但我不知道以后如何为每个子表单使用它。
我也知道我可以在视图中执行此操作,循环遍历实体并使用循环索引手动呈现每个集合元素,但我想在表单中执行此操作。
非常感谢。