douludi8413 2018-09-03 14:45
浏览 40

如何在表单有效时将Symfony中的表单数据映射到对象?

Imagine example form in Symfony:

public function buildForm(FormBuilderInterface $builder)
{
    $builder
        ->add('email', EmailType::class, [
            'constraints' => 
                new NotBlank(),
                new IsUnique(),
            ],
        ])
        ->add('password', PasswordType::class, [
            'constraints' => 
                new NotBlank(),
                new IsStrongEnough(),
            ],
        ])
}

Now when I submit the form and make sure it's valid, I'd like the $form->getData() to return my DTO called CreateAccountCommand:

final class CreateAccountCommand
{
    private $email;
    private $password;

    public function __construct(string $email, string $password)
    {
        $this->email = $email;
        $this->password = $password;
    }

    public function getEmail(): string
    {
        return $this->email;
    }

    public function getPassword(): string
    {
        return $this->password;
    }
}

Example controller:

$form = $this->formFactory->create(CreateAccountForm::class);
$form->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {
    $this->commandBus->dispatch($form->getData());

    return new JsonResponse([]);
}

I cannot use this class directly using the data_class, because the form obviously expects the model to have setters that allow null values. The form itself works perfectly well, so is the validation.

I tried using the Data mapper method, but the mapFormsToData method is invoked, before the validation.

Is this possible at all? Or am I supposed to get the data as array and create the object outside the form?

  • 写回答

2条回答 默认 最新

  • drsvw88664 2018-09-03 15:17
    关注

    Here is how I'm used to handle form with Symfony 4.1

    Let's assume you want a simple add form

    The Form

    class CreateAccountForm extends AbstractType
    {
        public function buildForm(FormBuilderInterface $builder)
        {
            //same method than yours
        }
    
        public function configureOptions(OptionsResolver $resolver)
        {
            $resolver->setDefaults(array('data_class' => 'App\Entity\CreateAccountCommand'));
        }
    }
    

    The controller

    public function add(Request $request)
    {
        $createAccountCommand = new CreateAccountCommand();
    
        //The object is "injected" to the form, that way, it's mapped when submitted
        $form = $this->get('form.factory')->create(CreateAccountForm::class, $createAccountCommand);
    
        //Form was submitted
        if ($request->isMethod('POST') && $form->handleRequest($request)->isValid())
        {
            //no need to getData(), the object $createAccountCommand is directly mapped to the form and can be used as is
            $em = $this->getDoctrine()->getManager();
            //persist, convert to json, or whatever
            $em->persist($createAccountCommand);
            $em->flush();
    
            return ($this->redirectToRoute('someRoute'));
        }
    
        //form not submitted, or has been submit with errors (isValid() == false)
        return ($this->render('account/add.html.twig',
                array('form' => $form->createView())));
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值