Search code examples
symfonysymfony-validator

Get validator constraints of an entity


I managed to inject the validator service into mine.

Now I can't figure out how to get the different constraints from an entity metadata .


Solution

  • // In your controller, get the validator:
    $validator = $this->get('validator');
    
    // Get Metadata for Class. You can use 'App\Bundle\Entity\YourEntity' as well
    $meta = $validator->getMetadataFor(YourEntity::class);
    
    // Used 'Default' as default Validation Group.
    $constraints = $meta->findConstraints('Default');
    

    http://symfony.com/doc/current/book/validation.html#using-the-validator-service

    Tested on Symfony 2.8. For other versions you might need a slightly different approach. If this is not working for you, please update your question with the Symfony version you are using.