If you have errors like “No media linked to the object” (Field error) and “The file could not be found.” (form error) in your SonataAdmin form or Symfony2 form when you are trying to add File constraints validation to SonataMedia, you are probably in the right place!
What I wanted
I needed to have a job application form containing 2 file fields (a CV and a motivation letter) on a Symfony2 website.
These 2 files should be PDF or DOC lesser than 4MB.
All job applications should be listed on the backoffice and files downloadable.
I already use the great Sonata bundles suite (Admin + Media + Formatter) and wanted to manage them with it.
First try with errors
So I first write my JobApply entity properties like these:
With this form:
But it can’t works like that, errors “No media linked to the object” and “The file could not be found.” appears because I tried to add File validation to a Sonata media entity!
Solution with Sonata InlineConstraint
After navigating throught Sonata CoreBundle/AdminBundle/MediaBundle documentation and the few stackoverflow/blog ressources availables I came to this solution: Using Sonata InlineConstraint
1. Create a service which will be called to validate your entity:
2. Add the InlineConstraint class constraint to your bundle’s validation configuration file:
You can see that I call the validate function on the service created previously.
3. Add the entity media properties like this:
4. Build your validate function:
You can use $errorElement->addConstraint(new NotBlank()) syntax instead of $errorElement->assertNotBlank() for all constraints.
Validator component will be used in all cases.
You can see that my validation service class is my form type class.
It’s not a best practise but like that, I have my validate function where my form is build..
I used Jasny Bootstrap to skin file input. It was not simple and maybe the subject of a next post.