RaphBlanchet RaphBlanchet - 2 months ago 36
PHP Question

Symfony - Multiple forms of same type

So I'm starting to learn Symfony. It looks like a pretty awesome Framework, but some concepts are still blur to me, so please excuse my question which might seems stupid to some of you.

So what I want to do is make a page where my user will be able to add multiple instances of the same Entity in the same page (let's say 5), so it's kinda like a "add items in bash" page (kind of like phpMyAdmin insert data page, where you can add multiple rows in one page).

I have made my FormType from my Entity, and everything works fine when I want to add 1 entity, but I have no idea how to handle multiple entities inserts.

I have tried through using a FormCollection, without any success (sorry I deleted my code so I can't show what I've tried...). I also tried generating 5 different forms with a loop and changing only their names, but I have no idea how to handle them.

If someone could show me the way, that would be really nice from you! Thanks in advance!

P.S I'm using Symfony 3.1.4

Answer

If you nest one form in another you can add as many forms as you want. So if the first form creates an entity... For example:

An entity form:

// src/AppBundle/Form/TaskType.php
namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class TaskType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('name')
            ->add('task');
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\Task',
        ));
    }
}

A container form that allows many forms to be added:

// src/AppBundle/Form/ProjectType.php
namespace AppBundle\Form;

use src/AppBundle/Form/TaskType.php
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;

class ProjectType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('tasks', CollectionType::class, array(
          'entry_type'   => TaskType::class,
          'allow_add'    => true // <- don't forgot this part :)
        ))
        ->add('save', SubmitType::class);
    }
}

You'll need to hook up the container form to some JavaScript so you can dynamically add more entity forms. That's described in detail in this cookbook article. Also, fair warning: this was typed up by a sleepy, lazy brain and comes untested and probably not functional. But it should put you on the right path :D good luck!