我有一个 Item 实体和一个 Image 实体,它们之间是 OneToOne 关系。我还有一个 ItemType 和 ImageType 表单。直到现在,当我遇到这种情况时,我分别使用这两个表单(将它们呈现为一个 html 表单)并在控制器或表单处理程序中设置关系。是否有一种-symfony- 方法可以将 ImageType 表单嵌入到 ItemType 中?一点代码可能会有所帮助。物品:
namespace Company\ItemBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use NewZaarly\ImageBundle\Entity\Image;
/**
* @ORM\Table()
* @ORM\Entity()
*/
class Item
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue
*/
private $id;
/**
* @ORM\Column(type="text")
*/
private $title;
/**
* @var \NewZaarly\ImageBundle\Entity\ImageItem
* @ORM\OneToOne(targetEntity="NewZaarly\ImageBundle\Entity\ImageItem", mappedBy="item", cascade={"persist", "merge", "remove"})
*/
private $image;
//other fields. Setters and getters
}
图片:
<?php
namespace Company\ImageBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
/**
* @ORM\Table()
* @ORM\Entity()
* @ORM\HasLifecycleCallbacks
*/
class Image
{
/**
* @Assert\File(maxSize = "2M", mimeTypes = {"image/png", "image/jpg", "image/jpeg"})
*/
protected $file;
/**
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(name="image", type="string", length=255, nullable=true)
*/
protected $image;
//other fields, setter and getters
}
图像类型
<?php
namespace Company\ImageBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class ImageType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('file', 'file', array('required' => true));
}
public function getName()
{
return 'image';
}
}
和 ItemType 形式
<?php
namespace Company\ItemBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Company\ImageBundle\Form\Type\ImageType;
class ItemType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('title', 'text');
$builder->add('image', new ImageType()); // <-- this is what I'd like to do
}
public function getDefaultOptions(array $options)
{
return array('data_class' => 'Company\ItemBundle\Entity\Item');
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array('data_class' => 'Company\ItemBundle\Entity\Item'));
}
public function getName()
{
return 'item';
}
}
这样做我在绑定请求时遇到错误,因为图像是数组而不是 Image 对象,这在 Item 类的 setImage 方法中是预期的。我的句柄函数很简单:
public function handle(FormInterface $form, Request $request)
{
if ($request->isMethod('POST')) {
$form->bind($request);
if ($form->isValid()) {
$item = $form->getData();
$this->itemManager->saveItem($item);
return true;
}
}
return false;
}
任何想法?我不喜欢我指定的第一种方式。