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?