【问题标题】:显示图像预览 Sonata Admin Bundle 无法加载类型“文件”
【发布时间】:2021-07-21 07:24:42
【问题描述】:

我正在尝试使用 Sonata Admin Bundle 3 版本显示预览图像,但我做不到。我在 RecipeAdmin.php 中收到此错误:无法加载类型“文件”:类不存在。

RecipeAdmin.php

<?php

declare(strict_types=1);

namespace App\Admin;

use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Show\ShowMapper;
use Sonata\Form\Type\CollectionType;
use Sonata\AdminBundle\Form\Type\ModelListType;



final class RecipeAdmin extends AbstractAdmin
{

    protected function configureDatagridFilters(DatagridMapper $datagridMapper): void
    {
        $datagridMapper
        ->add('title',null,['label' =>'Título'])
        ->add('image',null,['label' =>'Imagen'])
        ->add('description',null,['label' =>'Descripción'])
        ->add('score',null,['label' =>'Puntuación'])
        ->add('visible')
            ;
    }

    protected function configureListFields(ListMapper $listMapper): void
    {
        $listMapper
            ->add('id')
            ->add('user', CollectionType::class,['label' =>'Usuario'])
            ->add('title',null,['label' =>'Título'])
            ->add('image',null,['label' =>'Imagen'])
            ->add('description',null,['label' =>'Descripción'])
            ->add('score',null,['label' =>'Puntuación'])
            ->add('visible',null,['label' =>'Visible'])
            ->add('_action', null, [
                'label' => 'Acciones',
                'actions' => [
                    'show' => [],
                    'edit' => [],
                    'delete' => [],
                ],
            ]);
    }

    protected function configureFormFields(FormMapper $formMapper): void
    {
        

            $image = $this->getSubject();

            // use $fileFormOptions so we can add other options to the field
            $fileFormOptions = ['required' => false];
            if ($image && ($webPath = $image->getImage())) {
                // get the request so the full path to the image can be set
                $request = $this->getRequest();
                $fullPath = $request->getBasePath().'/'.$webPath;
    
                // add a 'help' option containing the preview's img tag
                $fileFormOptions['help'] = '<img src="'.$fullPath.'" class="admin-preview"/>';
                $fileFormOptions['help_html'] = true;
            }

            $formMapper
            ->add('title',null,['label' =>'Título'])
            ->add('image', 'file', $fileFormOptions)
            ->add('description',null,['label' =>'Descripción'])
            ->add('score',null,['label' =>'Puntuación'])
            ->add('visible')
            ;
    }

    protected function configureShowFields(ShowMapper $showMapper): void
    {
        $showMapper
            ->add('title',null,['label' =>'Título'])
            ->add('image',null,['label' =>'Imagen'])
            ->add('description',null,['label' =>'Descripción'])
            ->add('user', CollectionType::class)
            ->add('score',null,['label' =>'Puntuaciones'])
            ->add('visible')
            ;
    }
}

Recipe.php 实体

<?php

namespace App\Entity;

use App\Repository\RecipeRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass=RecipeRepository::class)
 */
class Recipe
{
    public function __construct() {
        $this->categories = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

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

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

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

    /** 
     * @ORM\ManyToOne(targetEntity="User", inversedBy="recipes")
     * @ORM\JoinColumn(nullable=false)
    */
    private $user;

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

    /**
     * @ORM\Column(type="boolean")
     */
    private $visible;

    /**
     * @ORM\ManyToMany(targetEntity="Category", inversedBy="recipe", cascade={"persist"})
     * @ORM\JoinTable(name="recipes_categories")
     */
    private $categories;

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

    public function setId(int $id)
    {
        $this->id = $id;

        return $this;
    }

    public function getTitle(): ?string
    {
        return $this->title;
    }

    public function setTitle(string $title): self
    {
        $this->title = $title;

        return $this;
    }

    public function getImage(): ?string
    {
        return $this->image;
    }

    public function setImage(string $image): self
    {
        $this->image = $image;

        return $this;
    }

    public function getDescription(): ?string
    {
        return $this->description;
    }

    public function setDescription(string $description): self
    {
        $this->description = $description;

        return $this;
    }

    public function getUser()
    {
        return $this->user;
    }

    public function setUser($user)
    {
        $this->user = $user;

        return $this;
    }

    public function getScore(): ?int
    {
        return $this->score;
    }

    public function setScore(?int $score): self
    {
        $this->score = $score;

        return $this;
    }

    public function getVisible(): ?bool
    {
        return $this->visible;
    }

    public function setVisible(bool $visible): self
    {
        $this->visible = $visible;

        return $this;
    }

    public function getCategories()
    {
        return $this->categories;
    }

    public function setCategories($categories)
    {
        $this->categories = $categories;

        return $this;
    }

    

    public function __toString()
    {
        return $this->getTitle();
    }

    public function addCategory(Category $category): self
    {
        if (!$this->categories->contains($category)) {
            $this->categories[] = $category;
        }

        return $this;
    }

    public function removeCategory(Category $category): self
    {
        $this->categories->removeElement($category);

        return $this;
    }
}

这是关于如何操作的链接:https://symfony.com/doc/current/bundles/SonataAdminBundle/cookbook/recipe_image_previews.html

https://sonata-project.org/bundles/admin/master/doc/cookbook/recipe_image_previews.html#showing-image-previews

在文档中解释说我必须使用“文件”类型字段,但是当我在我的项目中使用它时不会运行。

【问题讨论】:

    标签: symfony symfony4 sonata symfony-sonata


    【解决方案1】:

    这是文档中的错误,您应该使用 file 而不是 FileType::class 并添加:

    use Symfony\Component\Form\Extension\Core\Type\FileType;
        
    
    $formMapper
        ->add('title',null,['label' =>'Título'])
        ->add('image', FileType::class, $fileFormOptions)
    

    您仍然会遇到错误,例如:

    The form's view data is expected to be an instance of class Symfony\Component\HttpFoundation\File\File, but is a(n) string. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms a(n) string to an instance of Symfony\Component\HttpFoundation\File\File.
    

    在食谱中,他们告诉您创建一个图像实体,因此您应该添加它并按照所有步骤操作: https://sonata-project.org/bundles/admin/master/doc/cookbook/recipe_file_uploads.html

    我建议您安装并使用sonata media,而不是遵循这本食谱,集成更容易,并且它具有一些不错的功能,例如为您的上传制作不同的格式。

    【讨论】:

      猜你喜欢
      • 2023-04-01
      • 2019-03-13
      • 1970-01-01
      • 2016-09-03
      • 2016-05-31
      • 2016-04-20
      • 1970-01-01
      • 2012-07-15
      • 1970-01-01
      相关资源
      最近更新 更多