A Syfony Forms component is usually bound to some model either by defining default_mapping
option or passing the model object to $formBuilder-createForm($formType, $modelObject)
.
I am building a form that would initially only have one field: e-mail address. If the input address is found in the database, a transactional message with a login link should be sent. If such user does not exist, more fields must be added to the form so we can register said user.
My approach now uses a unbound form with events to check for the existense for the user.
How can I programatically assign the form the my User model if the user is not found to enable validation? Is there a better approach than using events?
<?php
namespace App\Form;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;
class RegistrationType extends AbstractType
{
private $em;
public function __construct(EntityManagerInterface $em) {
$this->em = $em;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('email', EmailType::class, ['label' => false, 'required' => true, 'mapped' => false]);
$builder->addEventListener(FormEvents::PRE_SUBMIT, array($this, 'onPreSubmitData'));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => null,
]);
}
public function onPreSubmitData(FormEvent $event) {
$form = $event->getForm();
$data = $event->getData();
$users = $this->em->getRepository(User::class);
dump($event->getForm()->isSubmitted());
if ($data['email'] && !$user = $users->findOneByEmail($data['email'])) {
$form->add('name', TextType::class);
$form->add('surname', TextType::class);
$form->add('tos', CheckboxType::class, ['required' => true, 'mapped' => false]);
$form->add('consentOn', CheckboxType::class);
$form->add('submit', SubmitType::class);
}
if (isset($data['submit'])) {
// Create new user
}
}
}