How to use the Symfony validator bundle to validate forms?

by darrion.kuhn , in category: PHP Frameworks , 2 years ago

How to use the Symfony validator bundle to validate forms?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lizzie , 2 years ago

@darrion.kuhn 

To use the Symfony Validator Bundle to validate forms, you can follow these steps:

  1. Install the Validator Bundle:composer require symfony/validator
  2. Create a form class with the desired fields and validation rules:use SymfonyComponentFormAbstractType; use SymfonyComponentFormExtensionCoreTypeTextType; use SymfonyComponentFormFormBuilderInterface; use SymfonyComponentValidatorConstraintsNotBlank; use SymfonyComponentValidatorConstraintsLength; class ContactFormType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('name', TextType::class, [ 'constraints' => [ new NotBlank(), new Length(['min' => 2, 'max' => 255]) ] ]) ->add('email', TextType::class, [ 'constraints' => [ new NotBlank(), new Email() ] ]) ->add('message', TextType::class, [ 'constraints' => [ new NotBlank(), new Length(['min' => 10, 'max' => 1000]) ] ]); } }
  3. In your controller, create an instance of the form and handle its submission:use SymfonyBundleFrameworkBundleControllerAbstractController; use SymfonyComponentHttpFoundationRequest; use SymfonyComponentRoutingAnnotationRoute; use SymfonyComponentFormExtensionCoreTypeSubmitType; class ContactController extends AbstractController { /** * @Route("/contact", name="contact") */ public function contact(Request $request) { $form = $this->createForm(ContactFormType::class) ->add('submit', SubmitType::class); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { // Do something with the form data } return $this->render('contact.html.twig', [ 'form' => $form->createView() ]); } }
  4. In your template, render the form with its fields and validation errors:{{ form_start(form) }} {{ form_row(form.name) }} {{ form_row(form.email) }} {{ form_row(form.message) }} {{ form_row(form.submit) }} {{ form_end(form) }} {% if form.errors|length > 0 %} <ul> {% for error in form.errors %} <li>{{ error.message }}</li> {% endfor %} </ul> {% endif %}


That's it! Now the form will be validated automatically based on the rules defined in the form class, and any validation errors will be displayed in the template.

Related Threads:

How to use the Symfony validator component to validate objects?
How to use the Symfony messenger bundle to handle messages?
How to use the Symfony security bundle to handle security tasks?
How to use the Symfony twig bundle to render templates?
How to use the Symfony maker bundle to generate code?
How to use the Symfony profiler bundle to debug your application?