首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Symfony 6中的VichUploaderBundle

Symfony 6中的VichUploaderBundle
EN

Stack Overflow用户
提问于 2022-03-31 15:39:43
回答 1查看 2K关注 0票数 3

我希望你能帮我,因为我在寻找,我迷路了。

我正在尝试上传图片在我的symfony 6项目与VichUploaderBundle。

我用的是医生:https://github.com/dustin10/VichUploaderBundle/blob/master/docs/usage.md#step-1-configure-an-upload-mapping

但我有个错误:

类"App\Entity\Client“不可上载。如果您使用注释来配置VichUploaderBundle,您可能只是忘记在实体的顶部添加@Vich\Uploadable。如果不使用注释,请检查配置文件是否位于正确的位置。在这两种情况下,清除缓存也可以解决问题。

我的vich_uploader.yaml:

代码语言:javascript
复制
vich_uploader:
    db_driver: orm


    mappings:
       clients_logo:
           uri_prefix: '%client_logo%'
           upload_destination: '%kernel.project_dir%/public%client_logo%'
           namer: Vich\UploaderBundle\Naming\SmartUniqueNamer

我的客户实体:

代码语言:javascript
复制
<?php

namespace App\Entity;

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

#[ORM\Entity(repositoryClass: ClientRepository::class)]
#[Vich\Uploadable]
class Client
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    private $id;

    #[ORM\Column(type: 'integer')]
    private $numero_client;

    /**
    * Some fields
    */

    /**
     * NOTE: This is not a mapped field of entity metadata, just a simple property.
     */
    #[Vich\UploadableField(mapping: 'clients_logo', fileNameProperty: 'logo')]
    private ?File $imageFile = null;

    #[ORM\Column(type: 'string', length: 255, nullable: true)]
    private $logo;


    #[ORM\Column(type: 'datetime', nullable: true)]
    private ?\DateTimeInterface $updatedAt = null;

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

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

    public function getLogo(): ?string
    {
        return $this->logo;
    }

    public function setLogo(?string $logo): self
    {
        $this->logo = $logo;

        return $this;
    }

    /**
     * If manually uploading a file (i.e. not using Symfony Form) ensure an instance
     * of 'UploadedFile' is injected into this setter to trigger the update. If this
     * bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
     * must be able to accept an instance of 'File' as the bundle will inject one here
     * during Doctrine hydration.
     *
     * @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 getBddClient(): ?BaseClient
    {
        return $this->bdd_client;
    }

    public function setBddClient(?BaseClient $bdd_client): self
    {
        $this->bdd_client = $bdd_client;

        return $this;
    }

    /**
     * @return Collection<int, Applis>
     */
    public function getApplis(): Collection
    {
        return $this->applis;
    }

    public function addAppli(Applis $appli): self
    {
        if (!$this->applis->contains($appli)) {
            $this->applis[] = $appli;
        }

        return $this;
    }

    public function removeAppli(Applis $appli): self
    {
        $this->applis->removeElement($appli);

        return $this;
    }

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

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

        return $this;
    }
}

我的FormType:

代码语言:javascript
复制
<?php

namespace App\Form;

use App\Entity\Client;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\CallbackTransformer;
use Symfony\Component\Form\FormBuilderInterface;
use Vich\UploaderBundle\Form\Type\VichImageType;
use Symfony\Component\Validator\Constraints\File;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;

class ClientType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('nom', TextType::class, [
                'label' => false,
            ])
            //Some add fields
            ->add('imageFile', VichImageType::class, [
                'required' => false
            ]);

        //Indispensable pour faire fonctionner le select du formulaire sinon erreur 500
        $builder->get('type_contrat')
            ->addModelTransformer(new CallbackTransformer(
                function ($typeContratArray) {
                    // transform the array to a string
                    return count($typeContratArray) ? $typeContratArray[0] : null;
                },
                function ($typeContratString) {
                    // transform the string back to an array
                    return [$typeContratString];
                }
            ));
    }

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

在我的形式中:

代码语言:javascript
复制
<div class="col-md-6">
    {{ form_row(form.imageFile, { 
        label: 'Logo',
        'attr': {'class': 'form-control'}
    }) }}
</div>

谁能解释这是怎么回事?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-31 19:22:43

假设您使用的是Php 8+,那么将包配置为使用属性而不是注释

代码语言:javascript
复制
vich_uploader:
    metadata:
        type: attribute

参考文献文档

编辑21 11月21日2022:作为包的v2attribute是默认值。

票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71695459

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档