Validation

Validation plays an essential role in modern applications. When talking about web applications, we can say we differentiate between two main types of validation; form data and persisted data validation. Taking input from a user via a web form should be validated, the same as any persisting data that goes into a database.

Symfony excels here by providing a Validation component based on JSR 303 Bean Validation drafted and available at http://beanvalidation.org/1.0/spec/. If we look back at our app/config/config.yml, under the framework root element, we can see that the validation service is turned on by default:

framework:
  validation:{ enable_annotations: true }

We can access the validation service from any controller class by simply calling it via the $this->get('validator') expression, as shown in the following example:

$customer = new Customer();

$validator = $this->get('validator');

$errors = $validator->validate($customer);

if (count($errors) > 0) {
  // Handle error state
}

// Handle valid state

The problem with the example above is that validation would never return any errors. The reason for this is that we do not have any assertions set on our class. The console auto-generated CRUD did not really define any constraints on our Customer class. We can confirm that by trying to add a new customer and typing in any text in the e-mail field, as we can see the e-mail wont be validated.

Let's go ahead and edit the src/AppBundle/Entity/Customer.php file by adding the @AssertEmail function to the $email property like the one shown here:

//…
use SymfonyComponentValidatorConstraints as Assert;
//…
class Customer
{
  //…
  /**
  * @var string
  *
  * @ORMColumn(name="email", type="string", length=255, unique=true)
  * @AssertEmail(
    *      checkMX = true,
    *      message = "Email '{{ value }}' is invalid.",
    * )
    */
  private $email;
  //…
}

The great thing about assertions constraints is that they accept parameters just as functions. We can therefore fine-tune individual constraints to our specific needs. If we now try to skip or add a faulty e-mail address, we would get a message like Email "[email protected]" is invalid.

There are numerous constraints available, for the full list we can consult the http://symfony.com/doc/current/book/validation.html page.

Constraints can be applied to a class property or a public getter method. While the property constraints are most common and easy to use, the getter method constraints allow us to specify more complex validation rules.

Let's take look at the newAction method of an src/AppBundle/Controller/CustomerController.php file as follows:

$customer = new Customer();
$form = $this->createForm('AppBundleFormCustomerType', $customer);
$form->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {
// …

Here we see an instance of a CustomerType form being bind to the Customer instance. The actual GET or POST request data is passed to an instance of a form via the handleRequest method. The form is now able to understand entity validation constraints and respond properly via its isValid method call. What this means is that we do not have to manually validate by using the validation service ourselves, the forms can do it for us.

We will continue to expand on validation features as we progress through individual bundles.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.95.38