【问题标题】:Use each child entity data for the options of a collection field type将每个子实体数据用于集合字段类型的选项
【发布时间】: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


    【解决方案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,
                   ))
          ;
       }
    }
    

    或类似

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-09
      • 1970-01-01
      • 2012-07-14
      • 2015-10-08
      • 2013-02-22
      相关资源
      最近更新 更多