In Symfony I can accept MIME types using:
/**
* @Assert\File( maxSize="10M", mimeTypes={"application/pdf", "image/png"} )
*/
public $file;
But how can I exclude something from that list? Let's say, I want to allow all uploads except for PHP files?
You could implement a Callback constraint via an assert. One advantage of this method is you can apply the error message to any field (or fields) in your form.
use Symfony\Component\Validator\ExecutionContext;
/**
* @ORM\Entity()
* @Assert\Callback(methods={"validateFile"})
*/
class MyEntity
{
public function validateFile(ExecutionContext $context)
{
$path = $context->getPropertyPath();
if (/* $this->file is not in allowed mimeTypes ... */) {
$context->setPropertyPath($path . '.file');
$context->addViolation("Invalid file mimetype", array(), null);
}
}
}
You don't need to create any callback to do this. Just make sure:
1) Set enable_annotations parameter as true in your app/config/config.yml:
# app/config/config.yml
framework:
validation: { enable_annotations: true }
2) Include properly the validation constraints on your entity file.
// YourEntity.php
use Symfony\Component\Validator\Constraints as Assert;
3) Use the annotation properly. Example:
// YourEntity.php
/**
* @Assert\File(
* maxSize="5242880",
* mimeTypes = {
* "image/png",
* "image/jpeg",
* "image/jpg",
* "image/gif",
* "application/pdf",
* "application/x-pdf"
* }
* )
*/
private $arquivo;
The above code is working fine on my Symfony 2.3.9.
[]s
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With