3

I am trying to make my app flexible by using configuration files instead of hard-coded stuffs, and come in troubles with validation constraints:

/**
 * @var ArrayCollection[SubjectTag]
 *
 * @ORM\OneToMany(targetEntity="SubjectTag", mappedBy="subject")
 * @Assert\Count(max = 15, maxMessage = "You can't create more than 15 tags.")
 * @Assert\Valid()
 */
protected $tags;

It would be nicer to do something like:

/**
 * @var ArrayCollection[SubjectTag]
 *
 * @ORM\OneToMany(targetEntity="SubjectTag", mappedBy="subject")
 * @Assert\Count(max = "%subject.max_tags%", maxMessage = "You can't create more than %subject.max_tags% tags.")
 * @Assert\Valid()
 */
protected $tags;

But by debugging I seen that my parameters were never recovered.

Any way to achieve this ?

1
  • 2
    As I mentioned in comments on the answer provided by Jason Roman, this should be added to symfony. It is wrong to say, that is not provided intentionally by design, because there are use cases in which you need to inject configuration parameters into built-in validators (developing a reusable 3rd party bundle to be used by the main application bundle) Commented Oct 14, 2017 at 12:15

1 Answer 1

1

The only way to do this is to create a custom validation constraint:

http://symfony.com/doc/current/cookbook/validation/custom_constraint.html

You can inject any parameters or services you need into the validator.

Sign up to request clarification or add additional context in comments.

4 Comments

It's by design for entities. They are basic classes describing the contract of what they are supposed to be, of which you can declare as $entity = new Entity(); without any dependencies. That's why you never inject services into entities directly.
Of course that's by design for entities, but I'm speaking about constraints configuration. Injecting the container in Constraint class and calling $container->getParameterBag()->resolveValue($options) might have been possible. Will try in this direction.
Keep in mind you'll only want to inject services in the Validator class of the Constraint, not the Constraint itself.
@JasonRoman This is a limitation and not a so called by design thing. Consider a third-party reusable bundle (inside vendor), which has basic property validation on abstract model classes, and needs to get the constraint values from application bundle which uses its basic definitions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.