Search code examples
phpsymfonysonatavichuploaderbundle

SonataAdmin + VichUploader not uploading image


I have set up VichUploaderBundle with SonataAdmin and I wan't to category entity upload image using sonata.

Form is rendered OK, entity save is Ok, send with multipart data and image is there. But it's not saved and there is no error or something to debug this.

config:

vich_uploader:
db_driver: orm
mappings:
    category_image:
        uri_prefix: /uploads/images/category
        upload_destination: %kernel.root_dir%/../web/uploads/images/category
        inject_on_load: true
        delete_on_remove: true
        delete_on_update: true
        namer: vich_uploader.namer_origname

CategoryAdmin:

        $formMapper
        ->add('title', 'text', ['label' => 'title'])
        ->add('description', 'textarea', ['required' => false, 'label' => 'description'])
        ->add('image', 'file',
            [
                'required' => false,
                'label' => 'image',
                'data_class' => 'Symfony\Component\HttpFoundation\File\File',
                'attr' => ['class' => 'sonata-medium-file'],
            ]
        );

CategoryEntity:

/**
 * @ORM\Column(type="string", length=255, name="image_name", nullable=true)
 */
protected $imageName;
/**
 * @Assert\File(
 *     groups={"list"},
 *     maxSize="500k",
 *     mimeTypes={"image/png", "image/jpeg", "image/pjpeg"},
 *     mimeTypesMessage = "constraint.mime_type"
 * )
 * @Vich\UploadableField(
 *     mapping="category_image",
 *     fileNameProperty="imageName"
 * )
 * @var File $image
 */
protected $image;

POST: content

Content-Disposition: form-data; name="s5519586317457[image]"; filename="ico.png"

Content-Type: image/png

file form


Solution

  • There are two things to know with VichUploaderBundle and Doctrine:

    • if the only field updated by the form is the file, Doctrine won't detect the change and it won't be persisted (this link explains why and how to work around that);
    • the bundle triggers the upload mechanism only when Symfony\Component\HttpFoundation\File\UploadedFile objects are present in the uploadable fields so defining a data_class option for your fields breaks that (you can safely remove it).

    N.B : you might also want to check that your entity is defined as @Vich\Uploadable