Symfony 4 - VichUploaderBundle - имя файла не сохранено в базе данных - PullRequest
0 голосов
/ 04 апреля 2020

У меня есть объект "Поддержка", с которым я хочу связать файл (PDF, DO C, ...). Я следил за документацией и некоторыми видео, чтобы помочь, но у меня всегда есть эта ошибка:

SQLSTATE[23000]: Integrity constraint violation: 1048 The field 'filename' can't be empty (null)

, и у меня нет никакого сопротивления в моей базе данных. вот моя сущность "Поддержка": `

        namespace App\Entity;

        use Doctrine\Common\Collections\ArrayCollection;
        use Doctrine\Common\Collections\Collection;
        use Doctrine\ORM\Mapping as ORM;
        use Symfony\Component\HttpFoundation\File\File;
        use Vich\UploaderBundle\Mapping\Annotation as Vich;

        /**
         * @ORM\Entity(repositoryClass="App\Repository\SupportRepository")
         * @Vich\Uploadable
         */
        class Support
        {
            /**
             * @ORM\Id()
             * @ORM\GeneratedValue()
             * @ORM\Column(type="integer")
             */
            private $id;

            /**
             * @var string|null
             * @ORM\Column(type="string", length=255)
             * 
             */
            private $filename;
            /**
             * @Vich\UploadableField(mapping="support_file", fileNameProperty="filename", size="fileSize")
             * @var File|null
             */
            private $supportFile;

            /**
             * @ORM\Column(type="integer")
             *
             * @var int|null
             */
            private $fileSize;

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

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

            /**
             * @ORM\Column(type="text", nullable=true)
             */
            private $desciption;

            /**
             * @ORM\ManyToMany(targetEntity="App\Entity\Salle", mappedBy="supports")
             */
            private $salles;

            /**
             * @ORM\ManyToOne(targetEntity="App\Entity\TypedeSupport", inversedBy="supports")
             * @ORM\JoinColumn(nullable=false)
             */
            private $typedeSupport;

            /**
             * @ORM\ManyToOne(targetEntity="App\Entity\Matiere", inversedBy="supports")
             */
            private $matiere;

            public function __construct()
            {
                $this->salles = new ArrayCollection();
            }

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

            public function getTitre(): ?string
            {
                return $this->titre;
            }

            public function setTitre(string $titre): self
            {
                $this->titre = $titre;

                return $this;
            }

            public function getUrl(): ?string
            {
                return $this->url;
            }

            public function setUrl(string $url): self
            {
                $this->url = $url;

                return $this;
            }

            public function getDesciption(): ?string
            {
                return $this->desciption;
            }

            public function setDesciption(?string $desciption): self
            {
                $this->desciption = $desciption;

                return $this;
            }

            /**
             * @return Collection|Salle[]
             */
            public function getSalles(): Collection
            {
                return $this->salles;
            }

            public function addSalle(Salle $salle): self
            {
                if (!$this->salles->contains($salle)) {
                    $this->salles[] = $salle;
                    $salle->addSupport($this);
                }

                return $this;
            }

            public function removeSalle(Salle $salle): self
            {
                if ($this->salles->contains($salle)) {
                    $this->salles->removeElement($salle);
                    $salle->removeSupport($this);
                }

                return $this;
            }

            public function getTypedeSupport(): ?TypedeSupport
            {
                return $this->typedeSupport;
            }

            public function setTypedeSupport(?TypedeSupport $typedeSupport): self
            {
                $this->typedeSupport = $typedeSupport;

                return $this;
            }

            public function getMatiere(): ?Matiere
            {
                return $this->matiere;
            }

            public function setMatiere(?Matiere $matiere): self
            {
                $this->matiere = $matiere;

                return $this;
            }

            public function getFilename(): ?string
            {
                return $this->filename;
            }
            public function setFilename(?string $filename): Support
            {
                $this->fileName = $filename;
                return $this; 
            }
            /**
             * @return null|File
             */
            public function getSupportFile(): ?File
            {
                return $this->supportFile;
            } 
            public function setSupportFile(?File $supportFile = null): Support
            {
                $this->supportFile = $supportFile;
                if (null !== $supportFile) {
                    // 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();
                }
                return $this; 
            }  

            public function setFileSize(?int $fileSize): void
            {
                $this->fileSize = $fileSize ;
            }

            public function getFileSize(): ?int
            {
                return $this->fileSize;
            }

        }

вот мой 'SupportType' для генерации формы:`

        namespace App\Form;

        use App\Entity\Support;
        use Symfony\Component\Form\AbstractType;
        use Symfony\Component\Form\Extension\Core\Type\FileType;
        use Symfony\Component\Form\FormBuilderInterface;
        use Symfony\Component\OptionsResolver\OptionsResolver;

        class SupportType extends AbstractType
        {
            public function buildForm(FormBuilderInterface $builder, array $options)
            {
                $builder
                    ->add('titre')
                    ->add('supportFile', FileType::class)
                    ->add('desciption')
                ;
            }

            public function configureOptions(OptionsResolver $resolver)
            {
                $resolver->setDefaults([
                    'data_class' => Support::class,
                ]);
            }
        }

и затем файл конфигурации: vich_uploader: db_driver: orm mappings: support_file: uri_prefix: /supports/teste upload_destination: '%kernel.project_dir%/public/supports/teste' namer: vich_uploader.namer_uniqid

представление : <div class="col-md-4"> <div class="card text-white bg-primary mb-3"> <div class="card-header text-center" style="font-size: 2.3rem;">Modifier le support</div> <div class="card-body"> <p class="card-text"><br> {% if error is defined and error %} <div class=" alert alert-danger" style="font-size: 1.3rem;"> {{error}} </div> {% endif %} {% for message in app.flashes('success') %} <div class=" alert alert-success" style="font-size: 1.7rem;"> {{message}} </div> {% endfor %}</p> <form method="post" action="" accept-charset="UTF-8"> <input type="hidden" name="action" value="users/send-password-reset-email"> <div class="form-group"> {{form_row(form.titre)}} </div> <div class="form-group"> {{form_row(form.supportFile)}} </div> <div class="form-group"> {{form_row(form.desciption)}} </div> {{ form_rest(form) }} <input type="submit" value="{{ button_label|default('Save') }}" class="btn btn-success col-12"> </form> <br><br> </div> </div><br> </div>

, несмотря на видео и форум, который я использовал, я не нашел никакого решения. Мне нужна ваша помощь, спасибо: -)

1 Ответ

0 голосов
/ 06 мая 2020

Для ввода «supportFile» необходимо указать VichFileType :: class, а не FileType :: class

class SupportType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
        ->add('titre')
        ->add('supportFile', VichFileType::class)
        ->add('desciption')
        ;
    }
...
}

do c: https://github.com/dustin10/VichUploaderBundle/blob/master/docs/form/vich_file_type.md

...