简体   繁体   中英

symfony2 assert a file type from within a form throws unexpectedTypeException

With symfony2 / doctrine 2, I want to use validation constraints to perform checks on an uploaded file in my application.

As the underlying entity is a general media entity which could be used for different kind of media across the website, I want to put those validation constraints in the relevant form types.

When I don't put any assert the upload is correctly done. When doing so, I get the following error :

Expected argument of type "string", "Doctrine\ORM\PersistentCollection" given
Stack Trace
in vendor/symfony/symfony/src/Symfony/Component/Validator/Constraints/FileValidator.php at line 119   -
        }
        if (!is_scalar($value) && !$value instanceof FileObject && !(is_object($value) && method_exists($value, '__toString'))) {
            throw new UnexpectedTypeException($value, 'string');
        }
        $path = $value instanceof FileObject ? $value->getPathname() : (string) $value;

My form type :

    ->add('medias', 'collection', array(
            'type' => new MediaType(),
            'by_reference' => false,
            'label'=>'Images et vidéos',
            'allow_add' => true,
            'allow_delete' => true,
            'required' => false,
            'cascade_validation' => true,
            'constraints' => array(
                new Assert\File(array('mimeTypes' => array("video/mpeg"), 'mimeTypesMessage' => "The file is not a video"))
            ),
            'attr'=>array(
                'data-toggle'=>"tooltip",
                'data-placement'=>"top",
                'title'=>"Ajoutez des images ou vidéos pour décrire la recette",
            )))

What am I doing wrong ?

Arf, I was tired, I should put this assert into another Assert\\All. I'm getting the error because it is a collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM