Synfony

Page 138

5 } else { 6 // ... 7 }

Inside the template, you can output the list of errors exactly as needed: Listing 11-6

1 2 3 4 5 6 7

{# src/Acme/BlogBundle/Resources/views/Author/validate.html.twig #} <h3>The author has the following errors</h3> <ul> {% for error in errors %} <li>{{ error.message }}</li> {% endfor %} </ul>

Each validation error (called a "constraint violation"), is represented by a ConstraintViolation4 object.

Validation and Forms The validator service can be used at any time to validate any object. In reality, however, you'll usually work with the validator indirectly when working with forms. Symfony's form library uses the validator service internally to validate the underlying object after values have been submitted and bound. The constraint violations on the object are converted into FieldError objects that can easily be displayed with your form. The typical form submission workflow looks like the following from inside a controller: Listing 11-7

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

// ... use Acme\BlogBundle\Entity\Author; use Acme\BlogBundle\Form\AuthorType; use Symfony\Component\HttpFoundation\Request; public function updateAction(Request $request) { $author = new Author(); $form = $this->createForm(new AuthorType(), $author); if ($request->isMethod('POST')) { $form->bind($request); if ($form->isValid()) { // the validation passed, do something with the $author object return $this->redirect($this->generateUrl(...)); } } return $this->render('BlogBundle:Author:form.html.twig', array( 'form' => $form->createView(), )); }

4. http://api.symfony.com/2.2/Symfony/Component/Validator/ConstraintViolation.html

PDF brought to you by generated on March 18, 2013

Chapter 11: Validation | 138


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.