Quantcast
Channel: Active questions tagged symfony4 - Stack Overflow
Viewing all articles
Browse latest Browse all 3916

How to map form data in Symfony to an object only when form is valid?

$
0
0

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?


Viewing all articles
Browse latest Browse all 3916

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>