symfony嵌入式集合形成具有不同名称的重复字段

时间:2014-07-08 09:44:34

标签: forms symfony collections

我有2个实体:注释实体和注释文档实体,它们与“oneToMany”,“manyToOne”关联连接,因此允许注释包含许多文件。

我使用FormBuilderInterface构建了CommentType和DocumentType类:

//CommentType
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->setAction($options['action']);
    $builder->add('comment');
    $builder->add('documents', 'collection', array(
        'type' => new DocumentType(),
        'allow_add' => true,
        'allow_delete' => true
    ));
    $builder->add('save', 'submit');
}


//DocumentType
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('file');
}

渲染的表单包含注释输入字段和文件上传字段,一切都很好,但我需要复制具有不同名称的字段,如下所示:

            _____________________
           |comment 1            |
 Category1 |                     |
 Comment   |                     |
           |                     |
           |                     |
           |_____________________|
                           ______________________
Category1 Document upload |Upload document button|

            _____________________
           |comment 2            |
 Category2 |                     |
 Comment   |                     |
           |                     |
           |                     |
           |_____________________|
                           ______________________
Category2 Document upload |Upload document button|

我还需要上传输入的“allow_add”功能,所以问题是,我该怎么做?

1 个答案:

答案 0 :(得分:1)

如果其他人在这个或类似问题上遇到麻烦,我所做的就是:

在CommentType类中,我创建了PRE_SET_DATA事件

$builder->addEventListener(
    FormEvents::PRE_SET_DATA,
    function(FormEvent $event) {
        $form = $event->getForm();
        $comment = $event->getData();
        if ($comment->getCategory() === 'category_1') {
            $form->add('comment', 'textarea', array(
                'label' => 'Category 1'
            ));
        } else {
            $form->add('comment', 'textarea', array(
                'label' => 'Category 2'
            ));
        }
    }
);

然后只需添加文档类型

$builder->add('documents', 'collection', array(
    'type' => new DocumentType(),
    'allow_delete' => true,
    'allow_add' => true,
    'by_reference' => false,
    'label' => false
));