The Symfony2 form component has a very nice way of validating: using annotations. These validation annotations give you the ability to annotate one or more invariants in the documentation of the properties of your class. These are automatically read and validated! Talking about up-to-date documentation. You can describe invariants like this in your entities:
/** * @Assert\Length(min=2, max=255) */ private $company_name;
Since we’re living in a world where it’s easy to pick the precise components you want with composer, that’s exactly what we’re going to do. This article is for people using the symfony/form component or the hostnet/form-twig-bridge that want to use the validation annotations.
If you don’t have the form framework up and running yet, read this readme first.
Step 1: Including required components
Next to the form and validation components you’re also need to require these packages in your composer.json:
"doctrine/annotations": ">=1.0", "doctrine/cache": ">=1.0"
These are two small libraries, originally part of Doctrine, but very usable without it as well.
Step 2: Read the validation annotations
Using the form-twig-bridge:
Or using the raw Symfony2 components:
$builder = Validation::createValidatorBuilder(); $builder->enableAnnotationMapping();
Step 3: Ensure validators are autoloaded
Every annotation has it’s own class. The AnnotationRegistry has explicitly disabled the default autoloading, so you have to register any classes you want to be included yourself. It has a PSR-0 compatible autoloader inside.
Since we want to use the form framework, lets register those classes. Put the following code in a file that is executed each request.
$vendor_dir = 'fill in yourself'; $namespace = 'Symfony\\Component\\Validator\\Constraints\\'; $directory = $vendor_dir . '/symfony/validator'; AnnotationRegistry::registerAutoloadNamespace($namespace, $directory);
If you want to add custom validatiors yourself, don’t forget to autoload these as well.
Step 4: Enable cascade_validation if you have embedded forms
If you have any embedded forms, be sure that the cascade_validation option is set to “true”, since otherwise the annotations of the embedded forms won’t be read.
// In the setDefaultOptions function $resolver->setDefaults(array('cascade_validation' => true));
That’s all it takes to enable the validation annotations to be read by the Symfony2 form component using the Doctrine annotation driver.