【发布时间】:2012-09-02 07:15:13
【问题描述】:
我在 symfony 2.0 中构建这个表单,由于某种原因,当我从数据库中检索一个对象并将其放入一个对象时,当我想保存它时它消失了,所以我收到以下错误:
Catchable Fatal Error: Argument 1 passed to MelvinLoos\CMS\CoreBundle\Entity\Page::setParent()
must be an instance of MelvinLoos\CMS\CoreBundle\Entity\Page, null given,
called in vendor\symfony\src\Symfony\Component\Form\Util\PropertyPath.php on line 347
and defined in src\MelvinLoos\CMS\CoreBundle\Entity\Page.php line 233
我的代码:
public function popupChildAction($parentid)
{
$entity = new Page();
$entity->setWebsite($this->getWebsite());
$parent = $this->getDoctrine()
->getRepository('MelvinLoosCMSCoreBundle:Page')
->findOneById($parentid);
if (!$parent)
{
throw $this->createNotFoundException('No parent found with given id: "' . $parentid . '"');
}
$entity->setParent($parent);
$entity->setCreatedBy($this->getUser());
//$entity->setPageType();
$form = $this->createForm(new PageChildType(), $entity);
$request = $this->getRequest();
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('page_show', array('id' => $entity->getId())));
}
return $this->render('MelvinLoosCMSCoreBundle:Page:new_popup.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
'parent' => $parent
));
}
如您所见,我输入了一个 if 语句来检查 $parent 是否已被填充,并且我还尝试了一个 var_dump 来仔细检查,它显然是用一个对象填充的。但是由于某种原因,当我调用实体对象的 setParent() 函数时,它会用 null 填充它。
【问题讨论】:
-
var_dump($parent) 在 if(!$parent) 之前,它说什么?
-
我们需要从 Page 类中查看你的函数 setParent()
-
如果您查看错误,并不是控制器上的调用导致错误($entity->setParent($parent); 行),而是 symfony 进行的调用在 \Symfony\Component\Form\Util\PropertyPath.php,因此错误是在代码中的其他位置产生的。我的猜测是它与您的 PageChildType 有关。你能发布代码吗?
-
看来,您的表单类型有一个
parent字段,当您绑定表单时,它会尝试在父项上设置null(因为父项未提交)。抛出错误是因为你的 setParent 方法是setParent(Page $parent),而不是setParent(Page $parent = null),所以它不接受 null。我只是建议从您的表单类型中删除父字段。
标签: php forms symfony fatal-error