symfony:另一个表单中的表单获取作者(文章)



对象Article

/**
* @var Collection
* @ORMOneToMany(targetEntity="AppBundleEntityPhoto", mappedBy="article", cascade={"persist"})
*/
private $photos;

对象Photo在其侧面具有

/**
* @var Article
* @ORMManyToOne(targetEntity="AppBundleEntityArticle", 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字段?这样我就可以在表格中使用定义的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

类似地,如果您使用的是 CollectionType 字段,其中您的底层集合数据是一个对象(如 Doctrine 的 ArrayCollection(,那么如果您需要调用 adder 和 remover(例如 addAuthor(( 和 removeAuthor(((,则必须将 by_reference 设置为 false。

最新更新