我试图用Sonata Admin Bundle 3版本显示预览图像,但我做不到。我在RecipeAdmin.php中遇到了这个错误:无法加载类型"文件":类不存在。
RecipeAdmin.php
<?php
declare(strict_types=1);
namespace AppAdmin;
use SonataAdminBundleAdminAbstractAdmin;
use SonataAdminBundleDatagridDatagridMapper;
use SonataAdminBundleDatagridListMapper;
use SonataAdminBundleFormFormMapper;
use SonataAdminBundleShowShowMapper;
use SonataFormTypeCollectionType;
use SonataAdminBundleFormTypeModelListType;
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 AppEntity;
use AppRepositoryRecipeRepository;
use DoctrineCommonCollectionsArrayCollection;
use DoctrineCommonCollectionsCollection;
use SymfonyComponentHttpFoundationFileUploadedFile;
use DoctrineORMMapping as ORM;
/**
* @ORMEntity(repositoryClass=RecipeRepository::class)
*/
class Recipe
{
public function __construct() {
$this->categories = new DoctrineCommonCollectionsArrayCollection();
}
/**
* @ORMId
* @ORMGeneratedValue
* @ORMColumn(type="integer")
*/
private $id;
/**
* @ORMColumn(type="string", length=255)
*/
private $title;
/**
* @ORMColumn(type="string", length=255)
*/
private $image;
/**
* @ORMColumn(type="string", length=255)
*/
private $description;
/**
* @ORMManyToOne(targetEntity="User", inversedBy="recipes")
* @ORMJoinColumn(nullable=false)
*/
private $user;
/**
* @ORMColumn(type="integer", nullable=true)
*/
private $score;
/**
* @ORMColumn(type="boolean")
*/
private $visible;
/**
* @ORMManyToMany(targetEntity="Category", inversedBy="recipe", cascade={"persist"})
* @ORMJoinTable(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-图像预览
在文档中解释说,我必须使用"file"类型字段,但当我在项目中使用它时,它不会运行。
这是文档中的一个错误,您应该使用FileType::class
而不是file
并添加:
use SymfonyComponentFormExtensionCoreTypeFileType;
$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 SymfonyComponentHttpFoundationFileFile, 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 SymfonyComponentHttpFoundationFileFile.
在食谱中,他们告诉你创建一个图像实体,所以你应该添加它,并遵循所有步骤:https://sonata-project.org/bundles/admin/master/doc/cookbook/recipe_file_uploads.html
我建议你不应该遵循这本食谱,而应该安装和使用sonata媒体,集成更容易,而且它有一些不错的功能,比如为你的上传制作不同的格式。