Yurii Nikytenko
Yurii Nikytenko

Reputation: 35

How to use VichUploaderBundle in CrudController's configureFields

Images aren't saving with settings below

public function configureFields(string $pageName): iterable
    {
        return [
            ImageField::new('imageFile')->setBasePath('%app.path.product_images%'),
        ];
    }

Upvotes: 0

Views: 2452

Answers (3)

jowilf
jowilf

Reputation: 31

This working for me...

First create VichImageField

use EasyCorp\Bundle\EasyAdminBundle\Contracts\Field\FieldInterface;
use EasyCorp\Bundle\EasyAdminBundle\Field\FieldTrait;
use Vich\UploaderBundle\Form\Type\VichImageType;

class VichImageField implements FieldInterface
{
    use FieldTrait;

    public static function new(string $propertyName, ?string $label = null)
    {
        return (new self())
            ->setProperty($propertyName)
            ->setTemplatePath('')
            ->setLabel($label)
            ->setFormType(VichImageType::class);
    }

}

And

public function configureFields(string $pageName): iterable
    {
        return [
           ImageField::new('imagename')->setBasePath($this->getParameter('app.path.product_images'))->onlyOnIndex(),
           VichImageField::new('imageFile')->hideOnIndex()
        ];
    }

More info here

https://symfony.com/doc/master/bundles/EasyAdminBundle/fields.html#creating-custom-fields

Upvotes: 3

umadesign
umadesign

Reputation: 256

You need the resolve the parameter first.

Instead of

ImageField::new('imageFile')->setBasePath('%app.path.product_images%')

Try

...
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

class ProductCrudController extends AbstractCrudController
{

    private $params;

    public function __construct(ParameterBagInterface $params)
    {
        $this->params = $params;
    }

    public function configureFields(string $pageName): iterable
    {
        return [          
            ImageField::new('imageFile')>setBasePath($this->params->get('app.path.product_images'))
        ];
    }

More info on getting the parameter here:

https://symfony.com/blog/new-in-symfony-4-1-getting-container-parameters-as-a-service

Upvotes: 0

Iwan Wijaya
Iwan Wijaya

Reputation: 2157

Make sure to change at least 1 doctrine mapped field in your setter, otherwise doctrine won't dispatch events. Here is an example from the docs:

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

public function setImageFile(File $image = null)
    {
        $this->imageFile = $image;

        // VERY IMPORTANT:
        // 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
        if ($image) {
            // if 'updatedAt' is not defined in your entity, use another property
            $this->updatedAt = new \DateTime('now');
        }
    }

Upvotes: 1

Related Questions