Create 2 different entities with same form in Symf

2019-03-31 08:42发布

问题:

Is it possible to create 2 related entities with the same form and action? If yes, how?

I want to create a new User and its related Questionnaire in a 1step registration.

Thanks, Luca

回答1:

You can create a form type for related entity (Questionnaire) and use it as a field type in User form type. It's called form nesting.

// src/Acme/DemoBundle/Form/Type/QuestionnaireType.php
namespace Acme\DemoBundle\Form\Type;

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

class QuestionnaireType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // create your form
    }

    public function getName()
    {
        return 'questionnaire';
    }
}

// src/Acme/DemoBundle/Form/Type/UserType.php
namespace Acme\DemoBundle\Form\Type;

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

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // ...
        $builder->add('questionnaire', new QuestionnaireType());
    }

    public function getName()
    {
        return 'user';
    }
}