显示图像预览 Sonata Admin Bundle 无法加载类型“文件”

问题描述

我正在尝试使用 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',['label' =>'Imagen'])
        ->add('description',['label' =>'Descripción'])
        ->add('score',['label' =>'Puntuación'])
        ->add('visible')
            ;
    }

    protected function configureListFields(ListMapper $listMapper): void
    {
        $listMapper
            ->add('id')
            ->add('user',CollectionType::class,['label' =>'Usuario'])
            ->add('title',['label' =>'Título'])
            ->add('image',['label' =>'Imagen'])
            ->add('description',['label' =>'Descripción'])
            ->add('score',['label' =>'Puntuación'])
            ->add('visible',['label' =>'Visible'])
            ->add('_action',[
                '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 = ['@R_404_3889@' => 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','file',$fileFormOptions)
            ->add('description',['label' =>'Puntuación'])
            ->add('visible')
            ;
    }

    protected function configureShowFields(ShowMapper $showMapper): void
    {
        $showMapper
            ->add('title',['label' =>'Descripción'])
            ->add('user',CollectionType::class)
            ->add('score',['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

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

解决方法

这是文档中的错误,您应该使用 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,它的集成更容易,而且它具有一些不错的功能,例如为您的上传制作不同的格式。