How do I pass a parameter to a validation constraint in Symfony2 - in yml
php, symfony, yaml
Solution
No, it's not currently possible.
It has nothing to do with YAML or XML or even service definitions. Validator component reads validation rules by itself - as you can see, the structure is quite different than for service definitions. Unfortunately, it does not replace the parameters in constraints.
The main logic resides in `\Symfony\Component\Validator\Mapping\Loader\YamlFileLoader` which is created by `\Symfony\Component\Validator\ValidatorBuilder::getValidator`.
You could make this happen by:
- Overriding definition of `validator.builder` service.
It's constructed using `%validator.builder.factory.class%::createValidatorBuilder`, but as you have to get parameter bag somehow, there is not enough dependencies - class factory is in use, not service factory.
- Creating new class, which extends `ValidatorBuilder`.
It should take parameter bag into constructor or via setter. It should be configured in step (1) to be passed here.
This class would create file loaders of another class (see 3), also pass that parameter bag into it.
- Creating new classes for `YamlFileLoader` and `YamlFilesLoader`. Additional 2 for each format that you would want to support.
It would additionally take parameter bag into constructor and override some functionality. For example, I think all parameter handling could be done in `newConstraint` method - iterate through options, resolve parameters, then call parent method with replaced options.
It's nice that Symfony could be extended like that (possibly not so nicely in this use-case), but I guess it would be easier to just write your own constraint with custom constraint validator, which would inject that parameter into it.
Also consider a wrapper around validator service - if you just need to replace the validation messages, you could replace the `validator` service, injecting original one into it. See http://symfony.com/doc/current/service_container/service_decoration.html for more information.
Problem
I am trying to add a bundle-wide parameter to my application so that I can add it to my Validation Constraint file (validation.yml): ``` myApp\myBundle\Entity\Contact: properties: name: - NotBlank: { message: "%myvariable%" } ``` I added my parameter normally in config.yml: ``` parameters: # Validation config myvariable: Please tell us your name. ``` But the page just renders the %myvariable% text, rather than the desired string. I also wish to use this parameter in my FormBuilderInterface when adding the validation messages to the page for usage in JavaScript. Does yml allow this? If not, how do I include such a parameter at a higher level?