dustin10 / VichUploaderBundle

A simple Symfony bundle to ease file uploads with ORM entities and ODM documents.
MIT License
1.85k stars 519 forks source link

Column 'image_name' cannot be null #1257

Closed CSRGH27 closed 2 years ago

CSRGH27 commented 2 years ago

Bug Report

Q A
BC Break no
Bundle version 1.19.0
Symfony version 5.4.2
PHP version 8.1.12

Summary

I can't save my images because the image_name field is null .

Current behavior

Every time I validate my form I get a db constraint violation for the image_name field which is empty "An exception occurred while executing a query: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'image_name' cannot be null"

How to reproduce

my vich_uploader.yaml:

vich_uploader:
    db_driver: orm
    mappings:
       housing_image:
           uri_prefix: /uploads/images_housing
           upload_destination: '%kernel.project_dir%/public/uploads/images_housing'

my image entity

<?php

namespace App\Entity;

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

/**
 * @ORM\Entity(repositoryClass=ImagesRepository::class)
 * @Vich\Uploadable()
 */
class Image
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /*
     * @Vich\UploadableField(mapping="housing_image", fileNameProperty="imageName")
     *
     */
    private $imageFile;

    /**
     * @ORM\ManyToOne(targetEntity=Housing::class, inversedBy="images")
     */
    private $housing;

    /**
     * @ORM\Column(type="datetime_immutable")
     */
    private $updatedAt;

    /**
     * @ORM\Column(type="string")
     *
     * @var string|null
     */
    private $imageName;

    /**
     *
     * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile|null $imageFile
     */
    public function setImageFile(?File $imageFile = null): void
    {
        $this->imageFile = $imageFile;

        if (null !== $imageFile) {
            // 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 \DateTimeImmutable();
        }
    }

    public function getImageFile(): ?File
    {
        return $this->imageFile;
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getHousing(): ?Housing
    {
        return $this->housing;
    }

    public function setHousing(?Housing $housing): self
    {
        $this->housing = $housing;

        return $this;
    }

    public function getUpdatedAt(): ?\DateTimeImmutable
    {
        return $this->updatedAt;
    }

    public function setUpdatedAt(\DateTimeImmutable $updatedAt): self
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

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

    /**
     * Set the value of imageName
     *
     * @param  string|null  $imageName
     *
     * @return  self
     */
    public function setImageName($imageName)
    {
        $this->imageName = $imageName;

        return $this;
    }
}

Expected behavior

I would like my images to be saved with automatic naming

Thank you for your help !

garak commented 2 years ago

How the image is uploaded?

CSRGH27 commented 2 years ago

I use Easy Admin 3 in this project, so I use a collectionField with a nested form (ImageType).

here my controller:

<?php

namespace App\Controller\Admin;

use App\Entity\Housing;
use App\Form\ImageType;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
use EasyCorp\Bundle\EasyAdminBundle\Field\BooleanField;
use EasyCorp\Bundle\EasyAdminBundle\Field\CollectionField;
use EasyCorp\Bundle\EasyAdminBundle\Field\NumberField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;

class HousingCrudController extends AbstractCrudController
{
    public static function getEntityFqcn(): string
    {
        return Housing::class;
    }

    public function configureFields(string $pageName): iterable
    {
        return [

            AssociationField::new ('owner')->hideOnForm(),
            NumberField::new ('superficie')->setLabel('Superficie du bien'),
            TextField::new ('address')->setLabel('Adresse du bien'),
            NumberField::new ('rooms')->setLabel('Nombre de pièces'),
            BooleanField::new ('parking')->setLabel('Parking ou garage'),
            BooleanField::new ('pool')->setLabel('Piscine'),
            BooleanField::new ('climatisation')->setLabel('Climatisation'),
            BooleanField::new ('balcony')->setLabel('Balcon'),
            BooleanField::new ('garden')->setLabel('Jardin'),

            CollectionField::new ('images')
                ->setEntryType(ImageType::class)
                ->onlyOnForms()
                ->setLabel('Vos images'),

        ];
    }

}

and my custom form :

<?php

namespace App\Form;

use App\Entity\Image;
use Symfony\Component\Form\AbstractType;
use Vich\UploaderBundle\Form\Type\VichFileType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class ImageType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('imageFile', VichFileType::class)
        ;
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => Image::class,
        ]);
    }
}
garak commented 2 years ago

Does it work without easyadmin?

CSRGH27 commented 2 years ago

I don't know if I have to try.

garak commented 2 years ago

Take your time and try. If it works, ask support to easyadmin. Otherwise, feel free to open another issue.