How to pass parameter to check constraint in Symfony2 - in yml

I am trying to add a parameter for the whole package to my application in order to add it to my validity limit file (validation.yml):

myApp\myBundle\Entity\Contact: properties: name: - NotBlank: { message: "%myvariable%" } 

I added my parameter usually in config.yml:

 parameters: # Validation config myvariable: Please tell us your name. 

But the page just displays the text% myvariable%, and not the desired line. I also want to use this parameter in my FormBuilderInterface when adding validation messages to a page for use in JavaScript. Does yml allow this? If not, how to enable such a parameter to a higher level?

+6
source share
1 answer

No, this is currently not possible.

This has nothing to do with YAML or XML, or even service definitions. The Validator component reads the validation rules on its own - as you can see, the structure is very different from the definition of services. Unfortunately, it does not replace the parameters in the restrictions.

The main logic is in \Symfony\Component\Validator\Mapping\Loader\YamlFileLoader , which is created by \Symfony\Component\Validator\ValidatorBuilder::getValidator .

You can do it:

  • Overriding the validator.builder service validator.builder .

It is built using %validator.builder.factory.class%::createValidatorBuilder , but since you need to somehow get the parameter package, there are not enough dependencies - the factory class is used, not the factory service.

  1. Create a new class that extends ValidatorBuilder .

It should take the parameter package to the constructor or through the setter. It must be configured in step (1), which must be passed here.

This class will create file loaders of another class (see 3), and also pass this package of parameters to it.

  1. Creating new classes for YamlFileLoader and YamlFilesLoader . An additional 2 for each format that you would like to support.

In addition, it will add a package of parameters to the constructor and override some functions. For example, I think that all parameter processing can be performed in the newConstraint method - iterating over the parameters, resolving the parameters, and then calling the parent method with the replaced parameters.


It's nice that Symfony can be extended this way (maybe not so good in this case), but I think it would be easier to just write your own constraint using a specialized validation constraint that would introduce this parameter into it.

Also consider the wrapper around the authentication service โ€” if you just need to replace the verification messages, you can replace the validator service by entering the original one in it. See http://symfony.com/doc/current/service_container/service_decoration.html for more details.

+1
source

All Articles