antanas_sepikas
antanas_sepikas

Reputation: 5704

symfony2 embeded collection form duplicate fields with different name

I have 2 entities: a comment entity, and a comment document entity, they are joined with "oneToMany", "manyToOne" association, thus allowing comment to have many files.

I have built CommentType and DocumentType classes using FormBuilderInterface:

//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');
}

The rendered form contains comment input field, and file upload field, everything is fine, but I need to duplicate those fields with different name like this:

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

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

I also need to "allow_add" functionality for upload inputs, so the question is, how should I do this?

Upvotes: 1

Views: 1370

Answers (1)

antanas_sepikas
antanas_sepikas

Reputation: 5704

If anyone else stumbles on this or similar problem, what I'v done is:

On CommentType class I have created PRE_SET_DATA event

$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'
            ));
        }
    }
);

and then simply added document type

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

Upvotes: 1

Related Questions