I want to create a form with a bound DTO. I assert three attributes the DTO:
- $firstName
- $lastName
- $image
One should only be asserted when I create a new object. The remaining two should always be asserted.
DTO
class MyDTO { /** * @AssertNotBlank() */ private ?string $firstName; /** * @AssertNotBlank() */ private ?string $lastName; /** * @AssertImage() * @AssertNotBlank(groups={MyFormType::VALIDATION_NEW}) */ private ?UploadedFile $image; ...
FormType
class MyFormType extends AbstractType { const VALIDATION_NEW = "new"; public function buildForm(FormBuilderInterface $builder, array $options) { //TODO: Assertion doesnt work $builder-> add('firstName', TextType::class, [ 'required' => false ]) ->add('lastName', TextType::class, [ 'required' => false ]) ->add('image', FileType::class, [ 'required' => false, ]); }
Controller
/** * @Route(path="/{myData}/edit", name="app.data.update") */ public function edit(MyData $myData, Request $request) { $dtoData = MyDTO::fromEntity($myData); $form = $this->createForm( MyFormType::class, $dtoData, [ 'validation_groups' => [ MyFormType::VALIDATION_NEW ], ] ); $form->handleRequest($request); if($form->isSubmitted() && $form->isValid()){ $this->repositoryClass->persist($dtoData->toEntity($myData)); return $this->redirectToRoute('app.data.show'); } return $this->render('app.edit.html.twig', [ 'myDataForm' => $form->createView() ]);
But even when I keep all fields blank, there are no messages about validation. The form allows me to save an empty form. I looked into the documentation but cant seem to find an answer. Why wont the assertions validate my form?
Advertisement
Answer
I am not sure, but adding “Default” to the validation groups should solve the problem.
/** * @Route(path="/{myData}/edit", name="app.data.update") */ public function edit(MyData $myData, Request $request) { $dtoData = MyDTO::fromEntity($myData); $form = $this->createForm( MyFormType::class, $dtoData, [ 'validation_groups' => [ MyFormType::VALIDATION_NEW, 'Default' ], ] ); $form->handleRequest($request); if($form->isSubmitted() && $form->isValid()){ $this->repositoryClass->persist($dtoData->toEntity($myData)); return $this->redirectToRoute('app.data.show'); } return $this->render('app.edit.html.twig', [ 'myDataForm' => $form->createView() ]);
By adding this option the Validator should take into consideration the assertions specified in the entity