symfony: [Validator] Attribute can not be applied on Controller method argument

Symfony version(s) affected

5.3.x

Description

Java Bean validation can be applied on method argument in a MVC Controller or other Jakarta EE components, but this does not work in Symfony.

I got the following exception when adding attributes on method arguments of a Controller.

 Uncaught Error: Attribute "Symfony\Component\Validator\Constraints\PositiveOrZero" cannot target parameter (allowed targets: method, prop
erty)

How to reproduce

Create a method like this.


  #[Route(path: "", name: "all", methods: ["GET"])]
  function all(string $keyword, #[PositiveOrZero] int $offset = 0, #[Positive] int $limit = 20): Response
  {
      $data = $this->posts->findByKeyword($keyword||'', $offset, $limit);
      return $this->json($data);
  }

Possible Solution

Make it work, and if validation failed throws an ContraintsVoilationException.

Additional Context

Add a built-in EventListener to handle this exception by default.

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 5
  • Comments: 16 (10 by maintainers)

Most upvoted comments

Let’s make things simple for now and put this in Validator. The registration of the service should then be done in FrameworkBundle.

@hantsy I’m willing to give it a try if you’re not already working on a PR for this.

@nicolas-grekas Where would this feature be implemented? I’m looking into the code and don’t see where I could put this new event listener.

I see that you’re using “bridges” to extend component capabilities into the framework. Would a new bridge “Validator” be a good candidate?