Validation with Symfony2 from a Drupal Perspective: DrupalCon Austin Session Notes

June 3, 2014 by Wayne Eaker
: Module Developers
Validation with Symfony2 from a Drupal Perspective: DrupalCon Austin Session Notes

Session Link: https://austin2014.drupal.org/session/validation-symfony2-drupal-perspective

  • Symfony is a set of reusable components. Drupal 8 uses 12 of these components.
  • Install with composer: "symfony/validator"

Validator Object

  • $validator = Validation::createValidator();
    $validator->validateValue('foo@bar.tld', new Email()); // Email is a constraint class

  • Combine constraints: $validator->value('wayne', array(new Length('min' => 5, 'max' => 15)), new Regex(array('pattern' => '/XXXX/'))

  • Can also validate whole objects.
  • validateValue(), validateProperty($user, 'email'), validationPropertyValue($user, 'email', 'foo@bar.tld'), validate($user)
  • ConstraintViolationList is a collection of validation failures

Constraint and ConstraintValidator

  • public properties = options for a Constraint subclass
  • class Regex, class RegexValidator. The Validator does the logic of validating in the validate() function
  • BasicConstraints: NotBlank(), Blank(), NotNull(), Null(), True(), False(), Url(), Ip(), Length(), Email()
  • Comparison Constraints
  • Date and Time constraints
  • Number and Financial Constraints: Currency(), CardScheme(), Iban(), Isbn()
  • Image Constraints: mimetypes, size, width, height
  • Collection Constraints: check all the values in an array

Object Validation Mapping

  • Can be definied in PHP, YML, XML, or Annotations
  • For each property of the object, you define the validation constratints in a validation builder
  • Annotations allow you to keep the validation rules right with the properties in the file.
  • Can have the validator validate sub-objects automatically.
  • Can apply constraints on methods as well as properties
  • You can apply Callback constraints to use methods to validate a property

Validation Groups

  • Allows for validation rules to change based on context
  • For example, user registration versus user edit profile
  • Group Sequence allows you to break validation into steps

Slides, for Example Code

Do you want to become an expert Drupal developer? Our classes will get you there in record time!

"The entire course was much more than I expected. I did attend a previous Drupal course, but there was no comparison. This ecourse rocks!"
Missi - Webmaster at a public library system