gpt4 book ai didi

php - Symfony2 OneToMany 嵌入表单不保存实体

转载 作者:可可西里 更新时间:2023-11-01 00:05:20 24 4
gpt4 key购买 nike

我对 Symfony2 中的 OneToMany 嵌入式表单一直存在问题。

这一次,实体被保存了,但没有保存对父类的引用。

我的 table 看起来像那样

| id | position | content | about_id |
| 29 | 1 | test 1 | NULL |

我不明白为什么这个 about_id 仍然是 NULL。

我的关系:

实体关于:

class About {
/*
....
*/

/**
* @ORM\OneToMany(targetEntity="AboutContent", mappedBy="about", cascade={"persist", "remove"})
*/
private $content;

/**
* Add content
*
* @param AboutContent $content
* @return About
*/
public function addContent(AboutContent $content)
{
$this->content[] = $content;

return $this;
}

/**
* Remove content
*
* @param AboutContent $content
*/
public function removeContent(AboutContent $content)
{
$this->content->removeElement($content);
}

/**
* Get content
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getContent()
{
return $this->content;
}
}

我的关于内容:

class AboutContent {
/**
* @ORM\ManyToOne(targetEntity="About", inversedBy="content")
*/
private $about;

/**
* Set about
*
* @param About $about
* @return AboutContent
*/
public function setAbout(About $about = null)
{
$this->about = $about;

return $this;
}

/**
* Get about
*
* @return About
*/
public function getAbout()
{
return $this->about;
}
}

我的 Controller 已由我的 crud 自动生成:

/**
* Creates a new About entity.
*
*/
public function createAction(Request $request)
{
$entity = new About();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);

if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();

$em->persist($entity);
$em->flush();

return $this->redirect($this->generateUrl('about_show', array('id' => $entity->getId())));
}

return $this->render('AdminBundle:About:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}

我的表单生成器:

$builder
->add('lang', 'choice', array(
'choices' => $this->langs,
'preferred_choices' => array('en'),
)) ->add('media')
->add('content', 'collection', array(
'type' => new AboutContentType(),
'allow_add' => true,
'allow_delete' => true,
'cascade_validation' => true
), array('label'=>'Texts'))
;

}

如果您找到解决方案,非常感谢。

最佳答案

大家好,经过一番搜索,我终于找到了答案。问题并非来 self 的实体或我的关系。它来 self 的表格。

在我的类型中,我只是省略了添加标签:'by_reference' => false

它解决了一切。

为了帮助你,如果你有同样的问题,下面是我的 build 者:

$builder->add(
'aboutContents',
'collection',
[
'type' => new AboutContentType(),
'allow_add' => true,
'allow_delete' => true,
'cascade_validation' => true,
'by_reference' => false,
],
[
'label' => 'Texts'
]
);

关于php - Symfony2 OneToMany 嵌入表单不保存实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27315194/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com