Answer the question
In order to leave comments, you need to log in
Why doesn't file validation work in Symfony?
Good afternoon.
There is a form class that has a collection of files (code below), everything works as it should, until you try to add a file with an invalid mimetype or larger, then no validation error occurs (file assertion at the very bottom)
# форма
class CreateMessageType extends BaseCreateMessageType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('body', 'wysiwyg_textarea', array(
'label' => false
));
$builder
->add(
'files', 'collection', array(
'type' => new MessageFileType(),
'allow_add' => true,
'by_reference' => false,
)
)
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'xxx\ForumBundle\Entity\Message',
'error_bubbling' => true,
'new_entry' => false,
));
}
}
# описание типа поля файлов
class MessageFileType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('file', 'file');
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'xxx\ForumBundle\Entity\MessageFiles',
'error_bubbling' => true,
'error_mapping' => array(
'upload' => 'file'
)
));
}
public function getName()
{
return 'file';
}
}
# ассерт файла
class MessageFiles
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* assert\File(
* maxSize = "3070k",
* mimeTypes = {
* "application/pdf",
* "application/x-pdf",
* "image/gif",
* "image/jpeg",
* "image/pjpeg",
* "image/png",
* "image/tiff",
* "image/vnd.wap.wbmp",
* "image/bmp",
* "image/x-bmp",
* "image/x-ms-bmp",
* "text/rtf",
* "application/rtf",
* "application/vnd.oasis.opendocument.text",
* "application/msword",
* "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
* },
* mimeTypesMessage = "Please upload a valid file"
* )
*
* assert\NotBlank()
*/
public $file;
# .........
}
Answer the question
In order to leave comments, you need to log in
maxSize = "3070k" - almost equal to 3M.
Just in case, check the limit set in the nginx client_max_body_size configuration, since it is 2M by default.
It is also worth looking into php.ini upload_max_filesize, post_max_size. Since if the file size > maxSize but < client_max_body_size - then this is a validation error, and if the size > client_max_body_size - then this is - 413 "Request Entity Too Large" - already a server error (what if it is configured not to show them) .
PS I understand that the answer may seem primitive to some, but I recently had a similar situation.
Take 2. symfony.com/doc/current/reference/forms/types/coll...
Try this one too.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question