Symfony 4 - VichUploaderBundle - 文件名没有在数据库中持久化。

问题描述 投票:0回答:1

我有一个实体 "支持",我想链接一个文件(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",用于从控制器中创建一个新的 "Support":`。

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,
                ]);
            }
        }

然后是配置文件.这里是我的实体 "Support".这里是我的 "newAction".创建一个新的 "Support "从控制器:`这里是我的 "SupportType".生成Form:`然后是配置文件: 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>

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

php file-upload symfony4 vichuploaderbundle
1个回答
0
投票

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

doc。https:/github.comdustin10VichUploaderBundleblobmasterdocsformvich_file_type.md。

© www.soinside.com 2019 - 2024. All rights reserved.