Add validation for household metadata

A new validation group 'household_metadata' has been added to the Household form. The 'waitingForBirth' field now has a type check, and for the 'waitingForBirthDate' field, an expression is added to ensure it's set if 'waitingForBirth' is true. Simultaneously, error handling for form submission has been enriched in the HouseholdController to display specific error messages.
This commit is contained in:
Julien Fastré 2024-04-08 14:52:40 +02:00
parent 29d53c53a4
commit 78a3dfd65e
Signed by: julienfastre
GPG Key ID: BDE2190974723FCB
4 changed files with 11 additions and 4 deletions

View File

@ -220,6 +220,12 @@ class HouseholdController extends AbstractController
'household_id' => $household->getId(),
]);
}
if ($form->isSubmitted() && !$form->isValid()) {
$this->addFlash('error', $this->translator->trans('This form contains errors'));
foreach ($form->getErrors() as $error) {
$this->addFlash('error', $error->getMessage());
}
}
return $this->render('@ChillPerson/Household/edit_member_metadata.html.twig', [
'household' => $household,
@ -275,7 +281,7 @@ class HouseholdController extends AbstractController
[
'household' => $household,
'positions' => $positions,
'form' => null !== $form ? $form->createView() : null,
'form' => $form?->createView(),
]
);
}

View File

@ -68,10 +68,12 @@ class Household
#[Serializer\Groups(['docgen:read'])]
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::BOOLEAN, name: 'waiting_for_birth', options: ['default' => false])]
#[Assert\Type('boolean', groups: ['household_metadata'])]
private bool $waitingForBirth = false;
#[Serializer\Groups(['docgen:read'])]
#[ORM\Column(type: \Doctrine\DBAL\Types\Types::DATE_IMMUTABLE, name: 'waiting_for_birth_date', nullable: true, options: ['default' => null])]
#[Assert\Expression('this.getWaitingForBirth() == false or value != null', message: 'The waiting for birth date must be set', groups: ['household_metadata'])]
private ?\DateTimeImmutable $waitingForBirthDate = null;
public function __construct()

View File

@ -43,6 +43,7 @@ class HouseholdType extends AbstractType
{
$resolver->setDefaults([
'data_class' => Household::class,
'validation_groups' => ['household_metadata'],
]);
}
}

View File

@ -115,11 +115,9 @@ final class HouseholdControllerTest extends WebTestCase
$form['household[commentMembers][comment]'] = 'This is a text **generated** by automatic tests';
$form['household[waitingForBirth]']->tick();
$form['household[waitingForBirthDate]'] = (new \DateTime('today'))
->add(new \DateInterval('P1M'))->format('Y-m-d');
->add(new \DateInterval('P10M'))->format('Y-m-d');
$this->client->followRedirects(false);
$this->client->submit($form);
$response = $this->client->getResponse();
self::assertEquals(302, $response->getStatusCode());