【问题标题】:Symfony 4 - VichUploaderBundle - filename is not persisted in the databaseSymfony 4 - VichUploaderBundle - 文件名未保存在数据库中
【发布时间】:2020-04-04 03:28:56
【问题描述】:

我有一个实体“支持”关于我想链接文件(PDF、DOC、...)的女巫。我已经按照文档和一些视频来提供帮助,但我总是遇到这个错误:

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;
            }

        }

在这里我的“newAction”从控制器创建一个新的“支持”:`

public function new(Request $request, $type, $salle, $matiere): Response
{
    $user = $this->getUser();
    if ($user->getRoles()==array('ROLE_PROF')) {
        $support = new Support();
        $type_de_support = $this->typedeSupportRepository->findOneBy(['intitule'=>$type]);
        $salle_de_support = $this->salleRepository->findOneBy(['nom'=>$salle]);
        $matiere_de_support = $this->matiereRepository->findOneBy(['intitule'=>$matiere]);
        $support->setTypedeSupport($type_de_support)
                ->addSalle($salle_de_support)
                ->setMatiere($matiere_de_support);
        $form = $this->createForm(SupportType::class, $support);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            dump($support);
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($support);
            $entityManager->flush();

            return $this->redirectToRoute('support_index',["type"=>$type,"salle"=>$salle ,"matiere"=>$matiere]);
        }`

这是我生成表单的“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">
{% 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>
</div>

尽管我使用了视频和论坛,但我没有找到任何解决方案。我需要你的帮助 谢谢:-)

【问题讨论】:

  • 没人帮我吗?

标签: php file-upload symfony4 vichuploaderbundle


【解决方案1】:

输入“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')
        ;
    }
...
}

文档:https://github.com/dustin10/VichUploaderBundle/blob/master/docs/form/vich_file_type.md

【讨论】:

  • 首先,感谢您的帮助。但我做了那个修改,但没有任何改变。
  • a précision:我使用的是 1.8 版本的 VichUploader
  • 我不知道是不是这样,但我会将函数“setFileName”和“setSupportFile”的返回类型“Support”更改为“void”或什么都不做。 1.8 的文档:link
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多