我的模型包含两个相关的类 - RealEstate 和 Image,对于 RealEstate 的一个实例,可以是很多 Image 的实例。由于 Image 类也可以与其他类结合使用,因此我选择了关系"一对多,单向联接表"。这可确保任何图像都不需要知道其使用位置。反过来,RealProperty 类与 $images 属性、getImages()、addImage(Image $image) 和 removeImage(Image $image) 方法一起提供,构造函数中的$images由空的 ArrayCollection 定义。因此,我有以下模型类。
1) 应用\实体\不动产\不动产
namespace AppEntityRealProperty;
use AppEntityPlatformImage;
use DoctrineCommonCollectionsArrayCollection;
use DoctrineORMMapping as ORM;
/**
* @ORMEntity(repositoryClass="AppRepositoryRealPropertyRealPropertyRepository")
* @ORMTable(name="real_property")
*/
class RealProperty
{
/**
* @ORMId
* @ORMGeneratedValue
* @ORMColumn(type="integer")
*/
private $id;
/**
* Many real properties have many images
* @ORMManyToMany(targetEntity="AppEntityPlatformImage", cascade={"all"})
* @ORMJoinTable(name="real_property_images",
* joinColumns={@ORMJoinColumn(name="real_property_id", referencedColumnName="id")},
* inverseJoinColumns={@ORMJoinColumn(name="image_id", referencedColumnName="id", unique=true)}
* )
*/
private $images;
/**
* RealProperty constructor
*/
public function __construct()
{
$this->images = new ArrayCollection();
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @return mixed
*/
public function getImages()
{
return $this->images;
}
/**
* @param Image $image
*/
public function addImage(Image $image)
{
if (!$this->images->contains($image)) {
$this->images->add($image);
}
}
/**
* @param Image $image
*/
public function removeImage(Image $image)
{
$this->images->removeElement($image);
}
}
2) 应用\实体\平台\图像
namespace AppEntityPlatform;
use DoctrineORMMapping as ORM;
use SymfonyComponentHttpFoundationFileFile;
use VichUploaderBundleMappingAnnotation as Vich;
/**
* @ORMEntity(repositoryClass="AppRepositoryPlatformImageRepository")
* @VichUploadable
*/
class Image
{
/**
* @ORMId
* @ORMGeneratedValue
* @ORMColumn(type="integer")
*/
private $id;
/**
* NOTE: This is not a mapped field of entity metadata, just a simple property.
*
* @VichUploadableField(mapping="image", fileNameProperty="imageName", size="imageSize")
*
* @var File
*/
private $imageFile;
/**
* @ORMColumn(type="string", length=255, nullable=false)
*
* @var string
*/
private $imageName;
/**
* @ORMColumn(type="integer")
*
* @var integer
*/
private $imageSize;
/**
* @ORMColumn(type="datetime", nullable=false)
* @var DateTime
*/
private $dateOfCreation;
/**
* @ORMColumn(type="datetime", nullable=false)
* @var DateTime
*/
private $dateOfChange;
/**
* Image constructor
*/
public function __construct()
{
$currentDate = new DateTime('NOW');
$this->dateOfCreation = $currentDate;
$this->dateOfChange = $currentDate;
}
/**
* @return mixed
*/
public function getId()
{
return $this->id;
}
/**
* @param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return File
*/
public function getImageFile(): ?File
{
return $this->imageFile;
}
/**
* 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|SymfonyComponentHttpFoundationFileUploadedFile $image
*/
public function setImageFile(?File $image = null): void
{
$this->imageFile = $image;
if (null !== $image) {
// 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->dateOfChange = new DateTimeImmutable();
}
}
/**
* @return string
*/
public function getImageName(): ?string
{
return $this->imageName;
}
/**
* @param string $imageName
*/
public function setImageName(?string $imageName)
{
$this->imageName = $imageName;
}
/**
* @return int
*/
public function getImageSize(): ?int
{
return $this->imageSize;
}
/**
* @param int $imageSize
*/
public function setImageSize(?int $imageSize)
{
$this->imageSize = $imageSize;
}
/**
* @return DateTime
*/
public function getDateOfCreation(): ?DateTime
{
return $this->dateOfCreation;
}
/**
* @param DateTime $dateOfCreation
*/
public function setDateOfCreation(?DateTime $dateOfCreation)
{
$this->dateOfCreation = $dateOfCreation;
}
/**
* @return DateTime
*/
public function getDateOfChange(): ?DateTime
{
return $this->dateOfChange;
}
/**
* @param DateTime $dateOfChange
*/
public function setDateOfChange(?DateTime $dateOfChange)
{
$this->dateOfChange = $dateOfChange;
}
}
对于每个类,我创建了适当的表单类型。
1) 应用\窗体\不动产\不动产类型
namespace AppFormRealProperty;
use AppEntityRealPropertyRealProperty;
use AppFormPlatformImageType;
use SymfonyComponentFormAbstractType;
use SymfonyComponentFormExtensionCoreTypeCollectionType;
use SymfonyComponentFormExtensionCoreTypeSubmitType;
use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentOptionsResolverOptionsResolver;
class RealPropertyType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('images', CollectionType::class, array(
'entry_type' => ImageType::class,
'label' => false,
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'by_reference' => false
))
->add('submit', SubmitType::class, [
'label' => 'Сохранить',
'attr' => [
'class' => 'btn btn-sm btn-primary col-6 mx-auto',
'style' => 'display: block;'
]
])
;
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppEntityRealPropertyRealProperty'
));
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'real_property_real_property';
}
}
2) 应用\表单\平台\图像类型
<?php
namespace AppFormPlatform;
use SymfonyComponentFormAbstractType;
use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentOptionsResolverOptionsResolver;
use VichUploaderBundleFormTypeVichImageType;
class ImageType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('imageFile', VichImageType::class, array(
'label' => false,
'required' => true
))
;
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppEntityPlatformImage'
));
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'platform_image';
}
}
这是我的控制器中的代码,其中创建了包含 CollectionType 的表单。
<?php
namespace AppControllerRealProperty;
use AppEntityRealPropertyRealProperty;
use AppFormRealPropertyRealPropertyType;
use SensioBundleFrameworkExtraBundleConfigurationRoute;
use SensioBundleFrameworkExtraBundleConfigurationMethod;
use SymfonyBundleFrameworkBundleControllerController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
/**
* Class RealPropertyController
*
* @Route("real_property")
* @package AppControllerRealProperty
*/
class RealPropertyController extends Controller
{
/**
* Creates a new real property entity
*
* @Route("/new", name="real_property_new")
* @Method({"GET", "POST"})
* @param Request $request
* @return SymfonyComponentHttpFoundationRedirectResponse|Response
*/
public function newAction(Request $request) {
$realProperty = new RealProperty();
$form = $this->createForm(RealPropertyType::class, $realProperty);
$form->handleRequest($request);
// dump($form->getData());
// dump($realProperty);
// dump($realProperty->getImages());
// dump($request->get('images'));
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($realProperty);
$em->flush();
return $this->redirectToRoute('real_property_index');
}
return $this->render('RealProperty/RealProperty/new.html.twig', [
'realProperty' => $realProperty,
'form' => $form->createView(),
]);
}
}
但是,必须包含图像实例的 ArrayCollection 始终为空,但在客户端,CollectionType 的所有子字段都包含其图像。
我们可以假设我错误地配置了 Vich/UploaderBundle,没有权限将图像保存在服务器目录中,数据库模式描述不正确......但是 - 不!一切都是正确的。特别是为此,我创建了一个单独的 ImageController,它在 newAction() 中创建 ImageType 表单,并且所有图像都安全地存储在数据库中。 因此,问题出在 ArrayCollection 级别或"一对多、单向与连接表"关系的级别。我认为如此。
请帮助找到这个陷阱。我将不胜感激。如有必要 - 我可以通过 git 共享项目。
提交表单时可以打开Symfony Profiler吗?
"表单"选项卡将为您提供如何处理数据的每个字段的详细信息,包括模型、规范化和视图格式。
这可能有助于您在表单组件处理之前和之后检查字段的类型。
我认为你应该使用VichImageType Field
.在此链接中,您可以看到正确的方法。为什么要手动设置Id
AppEntityPlatformImage
? 这是VichImageType代码:
use VichUploaderBundleFormTypeVichImageType;
class Form extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
// ...
$builder->add('imageFile', VichImageType::class, [
'required' => false,
'allow_delete' => true,
'download_label' => '...',
'download_uri' => true,
'image_uri' => true,
'imagine_pattern' => '...',
]);
}
}