Vichuploaderbundle: File size constraint in collectiontyp

Created on 11 Feb 2017  路  2Comments  路  Source: dustin10/VichUploaderBundle

Hi.
I was wondering: how do I get the file size constraint working, if I have a one-to-many relationship between an entity and uploaded files using the form CollectionType?

User FormType:

    ->add('UserFiles', CollectionType::class, array(
                'entry_type' => UserFilesType::class,
                'required' => false,
                'allow_add' => true,
                'allow_delete' => true,
                'by_reference' => false,
                'prototype' => true,
                'label' => false,
                'attr' => array(
                    'class' => 'file-collection',
                ),
            ))

UserFiles FormType:

 ->add('file', VichFileType::class, [
                'required' => false,
                'allow_delete' => true, // not mandatory, default is true
                'download_link' => true, // not mandatory, default is true
            ])

I have tryed using annotation:

    /**
     * NOTE: This is not a mapped field of entity metadata, just a simple property.
     *
     * @Vich\UploadableField(mapping="user_files", fileNameProperty="filename")
     * @Assert\File(
     *     maxSize = "1024k"
     *     )
     * @var File
     */

    private $file;

AND using callback:

    /**
     * @Assert\Callback(methods={"validate"})
     */
    public function validate(ExecutionContextInterface $context)
    {
        if ($this->file->getClientSize() > 1024) {
            $context
                ->buildViolation('File too big, max 1Mb')
                ->atPath('fileName')
                ->addViolation()
            ;
        }
    }

Upload, delete and so on all works fine, but I cannot seem to get the constraint working. Do you have any ideas?

Question

Most helpful comment

Hi Garak!

Wow, thx for the fast answer! That was the problem!
I also noticed that in order to show the errors with {{ form_errors(form) }} you have to set error_bubbling to true on the userfiletype (collection) AND on the filetype (nested in collection). Thanks for your help 馃憤

All 2 comments

Did you add @Assert\Valid on $UserFiles?

Hi Garak!

Wow, thx for the fast answer! That was the problem!
I also noticed that in order to show the errors with {{ form_errors(form) }} you have to set error_bubbling to true on the userfiletype (collection) AND on the filetype (nested in collection). Thanks for your help 馃憤

Was this page helpful?
0 / 5 - 0 ratings

Related issues

andrea-daru picture andrea-daru  路  3Comments

benIT picture benIT  路  3Comments

manguecreative picture manguecreative  路  4Comments

archie18 picture archie18  路  6Comments

jcg678 picture jcg678  路  6Comments