以编程方式将表单附加到Symfony中的模型

时间:2018-12-18 22:14:13

标签: php symfony symfony-forms

通常通过定义default_mapping选项或将模型对象传递到$formBuilder-createForm($formType, $modelObject)来将Syfony Forms组件绑定到某些模型。

我正在构建一个表单,该表单最初只有一个字段:电子邮件地址。如果在数据库中找到了输入地址,则应发送带有登录链接的事务性消息。如果不存在该用户,则必须将更多字段添加到表单中,以便我们可以注册该用户。

我的方法现在使用带有事件的未绑定表单来检查用户的existense。

如果未找到启用验证的用户,我该如何以编程方式将表单分配给我的用户模型?是否有比使用事件更好的方法?

<?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
        }
    }
}

0 个答案:

没有答案