@rollin
Form validation in Symfony is done using validation constraints. These constraints are defined as annotations in the entity class, or as separate validation files.
Here are the steps to use form validation in Symfony:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
use SymfonyComponentValidatorConstraints as Assert; class User { /** * @AssertNotBlank() */ private $username; /** * @AssertNotBlank() * @AssertEmail() */ private $email; // ... } |
In this example, we are using the NotBlank constraint to ensure that the username and email fields are not empty, and the Email constraint to ensure that the email field contains a valid email address.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
use SymfonyComponentFormExtensionCoreTypeTextType; use SymfonyComponentFormExtensionCoreTypeEmailType; use SymfonyComponentFormExtensionCoreTypeSubmitType; use SymfonyComponentFormFormBuilderInterface; use SymfonyComponentOptionsResolverOptionsResolver; class UserType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('username', TextType::class) ->add('email', EmailType::class) ->add('save', SubmitType::class) ; } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'data_class' => User::class, 'constraints' => [ new AssertValid(), ], ]); } } |
In this example, we are using the Valid constraint to ensure that the validation constraints defined in the entity class are applied to the form.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public function createAction(Request $request) { $user = new User(); $form = $this->createForm(UserType::class, $user); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { // Save the user to the database $entityManager = $this->getDoctrine()->getManager(); $entityManager->persist($user); $entityManager->flush(); return $this->redirectToRoute('user_list'); } return $this->render('user/create.html.twig', [ 'form' => $form->createView(), ]); } |
In this example, we are using the handleRequest method to handle the form submission, and the isValid method to check if the form data is valid according to the validation constraints.
That's it! With these steps, you can use form validation in Symfony.