【发布时间】:2018-04-26 07:55:51
【问题描述】:
我需要制作带有文件上传的表单字段,这也是 ManyToMany 实体的一部分。现在我的配置如下所示,并且可以正常工作...
class ProductTypeNew extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('price')
->add('description', TextareaType::class)
->add('quantity')
->add('file', FileType::class, array('label' => 'Zdjęcie'))
;
...但我需要在控制器中手动获取表单输入并设置为表单实体
if ($form->isSubmitted() && $form->isValid())
{
$image = new ShopProductImages();
$file = $product->getFile();
$fileName = $this->generateUniqueFileName().'.'.$file->guessExtension();
$file->move(
$this->getParameter('shop_images_directory'),
$fileName
);
$image->setFile($fileName);
$product->addShopProductImages($image);
$product->setFile($fileName);
$em = $this->getDoctrine()->getManager();
$em->persist($image);
$em->persist($product);
$em->flush();
我想做这样的事情(但它不起作用):
->add('shopProductImages', EntityType::class, array(
'by_reference' => false,
'entry_type' => FileType::class,
)
带有嵌入表单的新版本表单类型也会导致问题:
类型“Doctrine\Common\Collections\Collection|array”的预期值 对于关联领域 “AppBundle\Entity\ShopProducts#$shopProductImages”,得到 改为“Symfony\Component\HttpFoundation\File\UploadedFile”。
...具有以下配置:
产品类型新:
class ProductTypeNew extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', null, array('label' => 'Nazwa'))
->add('price', null, array('label' => 'Cena'))
->add('description', TextareaType::class, array('label' => 'Opis'))
->add('quantity', null, array('label' => 'Ilość'))
->add('shopProductImages', ShopProductsImagesType::class);
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => ShopProducts::class,
]);
}
ShopProductsImagesType:
class ShopProductsImagesType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('file', FileType::class, array('label' => 'Zdjęcie'))
;
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
// 'data_class' => ShopProductImages::class,
'data_class' => null,
]);
}
实体店产品:
/**
* ShopProducts
*
* @ORM\Table(name="shop_products")
* @ORM\Entity
*/
class ShopProducts
{
....
/**
* INVERSE SIDE
*
* @var \Doctrine\Common\Collections\Collection
*
* @ORM\ManyToMany(
* targetEntity="AppBundle\Entity\ShopProductImages",
* mappedBy="shopProducts",
* cascade={"persist"}
* )
*/
private $shopProductImages;
实体店ProductImages:
* @ORM\Entity
*/
class ShopProductImages
{
/**
* @var string
*
* @ORM\Column(name="file", type="text", length=255, nullable=true)
*/
private $file;
【问题讨论】:
标签: php symfony doctrine-orm symfony-forms entitymanager