1

我有两个实体,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();但我不知道以后如何为每个子表单使用它。

我也知道我可以在视图中执行此操作,循环遍历实体并使用循环索引手动呈现每个集合元素,但我想在表单中执行此操作。

非常感谢。

4

1 回答 1

1

我想你想要:

public function buildForm(FormBuilderInterface $builder, array $options)
{
   $data=someProcessingFunction($builder->getData()->getBs());
   $builder
      ->add('a_field')
      ->add('another_field')
      ->add('bs', 'collection', array(
               'type' => new BType(),
               'options' => array(
                  'label' => $data,
                  )
               ))
      ;
}

作为可能相关的,您可以在单独的 $builder->add 调用中将内容添加到末尾:

public function buildForm(FormBuilderInterface $builder, array $options)
{
   $builder->add('a_field');
   $builder->add('another_field');
   $data=someProcessingFunction($builder->getData()->getBs());
   $builder->add('bs', 'collection', array(
               'type' => new BType(),
               'options' => array(
                  'label' => $data,
                  )
               ))
      ;
}

如果您正在寻找每个唯一的标签,那么第二种方法更好:

public function buildForm(FormBuilderInterface $builder, array $options)
{
   $builder->add('a_field');
   $builder->add('another_field');

   $data=someProcessingFunction($builder->getData()->getBs());
   foreach ($data as $k=>$v){
   $builder->add('b'.$k, null, array(
                  'label' => $v,
               ))
      ;
   }
}

或类似的

于 2013-01-03T22:20:58.893 回答