symfony:另一个表单中的表单获取作者(文章)
symfony: Form inside of another form gets author (article)
对象 Article
有
/**
* @var Collection
* @ORM\OneToMany(targetEntity="AppBundle\Entity\Photo", mappedBy="article", cascade={"persist"})
*/
private $photos;
对象Photo
在其一侧有
/**
* @var Article
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\Article", inversedBy="photos")
*/
private $article;
我有一个对象Article
的表单,其中包含对象Photo
'的表单如下:
//article form building
->add('photos', CollectionType::class, [
'allow_delete' => true,
'allow_add' => true,
'entry_type' => PhotoType::class,
'entry_options' => [
'label' => false,
]
])
在我的 PhotoType
我有
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('image', ImageType::class, [
'context' => 'photo',
])
->add('description')
->add('url')
...
但是如何在 Photo
表单中设置 article
字段?以便我可以在 table 中使用定义的 article_id
列创建照片?当前,此表单中所有创建的照片都有 article_id NULL,换句话说,它们没有设置
在你的加法器中,你需要设置ID:
public function addPhoto(Photo $photo)
{
if (!$this->photos->contains($photo)) {
$this->photos[] = $photo;
$photo->setDocument($this);
}
return $this;
}
并且在您的表单中,您需要设置:'by_reference' => false
、https://symfony.com/doc/current/reference/forms/types/collection.html#by-reference
Similarly, if you're using the CollectionType field where your underlying collection data is an object (like with Doctrine's ArrayCollection), then by_reference must be set to false if you need the adder and remover (e.g. addAuthor() and removeAuthor()) to be called.
对象 Article
有
/**
* @var Collection
* @ORM\OneToMany(targetEntity="AppBundle\Entity\Photo", mappedBy="article", cascade={"persist"})
*/
private $photos;
对象Photo
在其一侧有
/**
* @var Article
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\Article", inversedBy="photos")
*/
private $article;
我有一个对象Article
的表单,其中包含对象Photo
'的表单如下:
//article form building
->add('photos', CollectionType::class, [
'allow_delete' => true,
'allow_add' => true,
'entry_type' => PhotoType::class,
'entry_options' => [
'label' => false,
]
])
在我的 PhotoType
我有
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('image', ImageType::class, [
'context' => 'photo',
])
->add('description')
->add('url')
...
但是如何在 Photo
表单中设置 article
字段?以便我可以在 table 中使用定义的 article_id
列创建照片?当前,此表单中所有创建的照片都有 article_id NULL,换句话说,它们没有设置
在你的加法器中,你需要设置ID:
public function addPhoto(Photo $photo)
{
if (!$this->photos->contains($photo)) {
$this->photos[] = $photo;
$photo->setDocument($this);
}
return $this;
}
并且在您的表单中,您需要设置:'by_reference' => false
、https://symfony.com/doc/current/reference/forms/types/collection.html#by-reference
Similarly, if you're using the CollectionType field where your underlying collection data is an object (like with Doctrine's ArrayCollection), then by_reference must be set to false if you need the adder and remover (e.g. addAuthor() and removeAuthor()) to be called.