Symfony: Error with File Constraint

2019-06-01 02:56发布

问题:

->add('shots','file', array(
    'multiple' => true,
    **'constraints' => array(
        new Constraints\Image(array(
            'maxSize' => '10M',
            'allowSquare' => false,
            'allowPortrait' => false,
            'minRatio' => 1.43,
            'maxRatio' => 2.4
        )),
    )**
))

This is part of a symfony form with intgrated form validator. But I get an error I dont understand:

UnexpectedTypeException: Expected argument of type "string", "array" given

Without the marked part everthing does work. I checked the reference of the form constraints, but I didn't get the solution ...

回答1:

This is Symfony\Component\Validator\Constraints\FileValidator that throw you this exception. Expecting your form value to be something that can be casted into string, but got array...

You should try to use the All constraint as a surrounding constraint of File, like this :

->add('shots','file', array(
    'multiple'    => true,
    'constraints' => array(
        new All(array(
            'constraints' => array(
                new Image(array(
                    'maxSize'       => '10M',
                    'allowSquare'   => false,
                    'allowPortrait' => false,
                    'minRatio'      => 1.43,
                    'maxRatio'      => 2.4
                ))
            )
        ))
    ))
))

See http://symfony.com/fr/doc/current/reference/constraints/All.html



回答2:

Try it this way:

use Symfony\Component\Validator\Constraints\Image;
...
...
...
->add('shots','file', array(
    'multiple'    => true,
    'constraints' => array(
        new Image(array(
            'maxSize'       => '10M',
            'allowSquare'   => false,
            'allowPortrait' => false,
            'minRatio'      => 1.43,
            'maxRatio'      => 2.4
        )),
    )
))