如何在Symfony 5上使用EasyAdmin 3和Vich上传器?

17

我一直在尝试在Symfony项目中使用VichUploader上传文件,已经使用了EasyAdmin 3。

我已经正确配置了一切,但是我遇到了这个错误:

"pieceJointeFile"图像字段必须使用setUploadDir()方法定义上传图像的目录。

<?php

namespace App\Entity;

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

My entity

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

    /**
     * @ORM\ManyToOne(targetEntity=Conducteur::class, inversedBy="inventaires")
     */
    private $conducteur;

    /**
     * @ORM\Column(type="date")
     */
    private $dateInventaire;

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

    /**
     * @Vich\UploadableField(mapping="pieceJointe", fileNameProperty="pieceJointe")
     */
    private $pieceJointeFile;

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

    public function __construct()
    {
        $this->updatedAt = new DateTime();
    }

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

    public function getConducteur(): ?Conducteur
    {
        return $this->conducteur;
    }

    public function setConducteur(?Conducteur $conducteur): self
    {
        $this->conducteur = $conducteur;

        return $this;
    }

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

    public function setDateInventaire(\DateTimeInterface $dateInventaire): self
    {
        $this->dateInventaire = $dateInventaire;

        return $this;
    }

    public function getPieceJointeFile() {
        return $this->pieceJointeFile;
    }

    public function setPieceJointeFile($pieceJointeFile): void
    {
        $this->pieceJointeFile = $pieceJointeFile;

        if($pieceJointeFile) {
            $this->updatedAt = new DateTime();
        }
    }

    public function getPieceJointe() {
        return $this->pieceJointe;
    }


    public function setPieceJointe($pieceJointe):self
    {
        $this->pieceJointe = $pieceJointe;
        return $this;
    }

    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }
}

文件上传配置

vich_uploader:
    db_driver: orm

    mappings:
        pieceJointe:
            uri_prefix: /files/pieceJointe
            upload_destination: '%kernel.project_dir%/public/files/pieceJointe'

最后是我的CRUD控制器

<?php

namespace App\Controller\Admin;

use App\Entity\Inventaire;
use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
use EasyCorp\Bundle\EasyAdminBundle\Field\DateField;
use EasyCorp\Bundle\EasyAdminBundle\Field\ImageField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use Vich\UploaderBundle\Form\Type\VichFileType;
use Vich\UploaderBundle\Form\Type\VichImageType;

class InventaireCrudController extends AbstractCrudController
{
    public static function getEntityFqcn(): string
    {
        return Inventaire::class;
    }


    public function configureFields(string $pageName): iterable
    {
        return [
            DateField::new('dateInventaire'),
            AssociationField::new('conducteur'),
            TextField::new('pieceJointeFile')->setFormType(VichFileType::class, [
                'delete_label' => 'supprimer?'
            ])->onlyOnForms(),
            ImageField::new('pieceJointe')->setBasePath('/files/pieceJointe')->onlyOnDetail(),
            ImageField::new('pieceJointeFile')->setFormType(VichImageType::class)
        ];
    }



    public function configureActions(Actions $actions): Actions
    {
        return $actions
            ->add(Crud::PAGE_INDEX, Action::DETAIL);
    }
}

最后,我想澄清的是,在使用TextField时它能正常工作。

6个回答

13
$imageFile = TextareaField::new('imageFile')->setFormType(VichImageType::class);

我用TextareaField替换了ImageField,然后它对我起作用了!!!

$imageFile = TextareaField

$image = ImageField


10

通过创建一个简单的字段类,您可以解决这个问题。

<?PHP

namespace App\Field;

use App\Form\MetaDataType;
use EasyCorp\Bundle\EasyAdminBundle\Contracts\Field\FieldInterface;
use EasyCorp\Bundle\EasyAdminBundle\Field\FieldTrait;
use Vich\UploaderBundle\Form\Type\VichImageType;

final class VichImageField implements FieldInterface
{
    use FieldTrait;

    public static function new(string $propertyName, ?string $label = 'Image'): self
    {
        return (new self())
            ->setProperty($propertyName)
            ->setLabel($label)
            // this template is used in 'index' and 'detail' pages
            ->setTemplatePath('admin/field/vich_image.html.twig')
            // this is used in 'edit' and 'new' pages to edit the field contents
            // you can use your own form types too
            ->setFormType(VichImageType::class)
            ->addCssClass('field-vich-image')
        ;
    }
}

然后在您的crud控制器中使用它

use App\Field\VichImageField;

...
yield VichImageField::new('image')->hideOnForm();
yield VichImageField::new('imageFile')->onlyOnForms();

这里使用两次是因为你需要image字段来呈现图片,而imageFile则用于表单。

{# admin/field/vich_image.html.twig #}
{% if field.value %}
  {% if field.value|match('/\.svg$/') %}
    <div class="thumbnail">
      {{ vich_uploader_asset(entity.instance, field.property ~ 'File', entity.fqcn) }}
    </div>
  {% else %}
    {% set html_id = 'ea-lightbox-' ~ field.uniqueId %}
    <a href="#" class="ea-lightbox-thumbnail" data-featherlight="#{{ html_id }}" data-featherlight-close-on-click="anywhere">
        <img src="{{ vich_uploader_asset(entity.instance, field.property ~ 'File', entity.fqcn)|imagine_filter('admin_thumbnail') }}" alt="{{ entity.name }}" class="img-fluid">
    </a>

    <div id="{{ html_id }}" class="ea-lightbox">
        <img src="{{ vich_uploader_asset(entity.instance, field.property ~ 'File', entity.fqcn)|imagine_filter('admin_full') }}" alt="{{ entity.name }}">
    </div>
  {% endif %}
{% else %}
    <span class="badge badge-secondary">
        Empty
    </span>
{% endif %}

1
你好,能否分享一下你的“vich_image.html.twig”源代码? - Johnny
1
嗨@Johnny,我已将其添加到我的答案中。 - Flash
1
谢谢。您可以分享一下您的2个图像过滤器admin_thumbnail和admin_full吗? - Johnny
1
一般来说,你根本不需要这些过滤器。但是如果你想要的话,可以通过liip/LiipImagineBundle进行配置,我的配置如下:liip_imagine: driver: "gd" filter_sets: admin_thumbnail: {quality: 75, filters: {thumbnail: {size: [120, 90], mode: outbound}}} admin_full: {quality: 90}请参阅此处的文档 https://symfony.com/doc/current/bundles/LiipImagineBundle/basic-usage.html - Flash
1
@Johnny 对于图像集合,这甚至更容易:只需为您的DeviceImage实体创建一个带有VichImage字段的表单,如 `$builder->add('imageFile', VichImageType::class)',并在您的集合字段'CollectionField::new('images') ->setEntryType(DeviceImageType::class) ->allowAdd() ->setFormTypeOptions(['by_reference' => false, ]);'中使用它。 - Flash
显示剩余6条评论

4
我发现EasyAdmin和VichUploaderBundle的文档中存在一个错误,会导致下一个异常: "imageFile"图像字段必须使用setUploadDir()方法定义上传图像的目录。
解决方案很简单:
//Entity
/**
  *
  * @Vich\UploadableField(mapping="video_image", fileNameProperty="imageName")
  *
  * @var File|null
*/
    private $imageFile;
//......

/**
  * @param File|null $imageFile
  * @return $this
*/
public function setImageFile(File $imageFile = null): self
{
    $this->imageFile = $imageFile;
    if (null !== $imageFile) {
        $this->updatedAt = new DateTime();
    }
  return $this;
}

//Admin Crud controller
// any type of field isnt correct except one
$coverImage = ImageField::new('imageFile')->setFormType(VichImageType::class); 

//this is a proper way of how to
$coverImage = Field::new('imageFile')->setFormType(VichImageType::class);

除了在vich_uploader.yaml中进行正确的配置外,不需要创建任何自定义字段类型或其他内容。


2

我有同样的问题。

我通过回到版本“easycorp/easyadmin-bundle”:”3.1.6”来解决它。

祝好运!


5
降级既不是一个好的解决方案,也不是一个安全的解决方案,特别是在上传捆绑文件(可能不安全)的情况下。 - Alexandre Tranchant

0
我有同样的问题。我通过在控制器中更改以下内容来解决它: use App\Field\VichImageField;
...
yield VichImageField::new('image')->hideOnForm();
yield VichImageField::new('imageFile')->onlyOnForms();

0

在你的 CrudController 中

    public function configureFields(string $pageName): iterable
    {
        $name = TextField::new('name');
        $description = TextField::new('description');
        $image = ImageField::new('image')
            ->setTemplatePath('admin/fields/vich_image.html.twig')
            ;
        $imageFile = Field::new('imageFile')
            ->setFormType(VichImageType::class)
            ;

        if (Crud::PAGE_INDEX === $pageName) {
            return [$name, $description, $image];
        } elseif (Crud::PAGE_DETAIL === $pageName) {
            return [$image];
        } elseif (Crud::PAGE_NEW === $pageName) {
            return [$name, $description, $imageFile];
        } elseif (Crud::PAGE_EDIT === $pageName) {
            return [$name, $description, $imageFile];
        }
    }

这里是稍微更新的admin/fields/vich_image.html.twig版本,适用于较小屏幕全屏显示:

{% if field.value %}
    <a href="#" data-bs-toggle="modal" data-bs-target="#imageModal{{ field.uniqueId }}">
        <img src="{{ vich_uploader_asset(entity.instance, 'imageFile')|imagine_filter('thumb') }}">
    </a>
    <div class="modal fade" id="imageModal{{ field.uniqueId }}" tabindex="-1" aria-labelledby="modal for {{ entity.instance.name }}" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-fullscreen-lg-down">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">{{ entity.instance.name }}
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <img src="{{ vich_uploader_asset(entity.instance, 'imageFile')|imagine_filter('creative_dim_down') }}">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
{% endif %}

供参考,这里是用于缩略图和图片尺寸缩放的liip过滤器

liip_imagine:

    # [...]

    filter_sets:
        cache: ~

        thumb:
            quality: 75
            filters:
                thumbnail: { size: [120, 90], mode: outbound }
                background: { size: [124, 94], position: center, color: '#000000' }

        creative_dim_down:
            quality: 90
            filters:
                scale:  
                    dim: [ 800, 1000 ]   

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接