Skip to content

Instantly share code, notes, and snippets.

@bahamut45
Last active August 30, 2016 10:25
Show Gist options
  • Save bahamut45/97b208870edeb9ca9f85a5fd26305f1a to your computer and use it in GitHub Desktop.
Save bahamut45/97b208870edeb9ca9f85a5fd26305f1a to your computer and use it in GitHub Desktop.
Symfony-Vich-UploaderBundle

Installation par composer

  • composer require vich/uploader-bundle

Activation du bundle dans app/AppKernel.php

<?php
class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            // ...
            new Vich\UploaderBundle\VichUploaderBundle(),
            // ...
        );
    }
}

Configuration dans app/config/config.yml

vich_uploader:
    db_driver: orm

Ajout dans le fichier de config du mapping dans app/config/config.yml

vich_uploader:
    db_driver: orm
    mappings:
        websites_image:
            uri_prefix:         /images/websites
            upload_destination: '%kernel.root_dir%/../web/uploads/images/websites'

Modifier votre entity pour ajouter un champ image

<?php

namespace Acme\DemoBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;

/**
 * @ORM\Entity
 * @Vich\Uploadable
 */
class Product
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    // ..... other fields

    /**
     * NOTE: This is not a mapped field of entity metadata, just a simple property.
     * 
     * @Vich\UploadableField(mapping="website_image", fileNameProperty="imageName")
     * 
     * @var File
     */
    private $imageFile;

    /**
     * @ORM\Column(type="string", length=255)
     *
     * @var string
     */
    private $imageName;

    /**
     * @ORM\Column(type="datetime")
     *
     * @var \DateTime
     */
    private $updatedAt;

    /**
     * If manually uploading a file (i.e. not using Symfony Form) ensure an instance
     * of 'UploadedFile' is injected into this setter to trigger the  update. If this
     * bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
     * must be able to accept an instance of 'File' as the bundle will inject one here
     * during Doctrine hydration.
     *
     * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $image
     *
     * @return Product
     */
    public function setImageFile(File $image = null)
    {
        $this->imageFile = $image;

        if ($image) {
            // It is required that at least one field changes if you are using doctrine
            // otherwise the event listeners won't be called and the file is lost
            $this->updatedAt = new \DateTime('now');
        }

        return $this;
    }

    /**
     * @return File|null
     */
    public function getImageFile()
    {
        return $this->imageFile;
    }

    /**
     * @param string $imageName
     *
     * @return Product
     */
    public function setImageName($imageName)
    {
        $this->imageName = $imageName;

        return $this;
    }

    /**
     * @return string|null
     */
    public function getImageName()
    {
        return $this->imageName;
    }
}

Mettre à jour votre base de donnée

php app/console doctrine:schema:update --dump-sql

ALTER TABLE website_links ADD image_name VARCHAR(255) DEFAULT NULL;

Ajouter un directory_namer permet par exemple d'avoir un sous dossier contenant l'id /images/websites/id/image.png au lieu de /images/websites/image.png

  • Créér un dossier dans votre bundle Acme\DemoBundle\Services;
  • Ajouter un fichier ImageDirectoryNamer.php dedans;
<?php
namespace AppBundle\DemoBundle\Services;

use Symfony\Component\Security\Core\SecurityContextInterface;

use Vich\UploaderBundle\Mapping\PropertyMapping;
use Vich\UploaderBundle\Naming\DirectoryNamerInterface;

use AppBundle\Entity\Product;

class ImageDirectoryNamer implements DirectoryNamerInterface
{

    public function directoryName($object, PropertyMapping $mapping)
    {
        return $object->getId();;
    }

}

Modifier la configuration pour lui dire de suivre le service app/config/config.yml

vich_uploader:
    db_driver: orm
    mappings:
        websites_image:
            uri_prefix:         /images/websites
            upload_destination: '%kernel.root_dir%/../web/uploads/images/websites'
            directory_namer: appbundle.demobundle.websites_image

Ajouter la definition de ce service dans services.yml

services:
    appbundle.demobundle.websites_image: 
        class: Appbundle\DemoBundle\Services\ImageDirectoryNamer

Modifier votre form type pour ajouter le champ file

    builder->add('imageFile')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment