2014-10-06 52 views
0

如果此字段之前具有值,則在將實體字段編輯爲NULL時出現錯誤。對於第一次堅持數據庫,我可以提交與NULL值。此錯誤發生時更改值回NULL:將實體字段編輯爲空symfony2

Catchable Fatal Error: Argument 1 passed to Sifo\SharedBundle\Entity\BlogMenu::setBlogPage() must be an instance of Sifo\SharedBundle\Entity\BlogPage, null given, called in C:\Sifony\vendor\symfony\symfony\src\Symfony\Component\PropertyAccess\PropertyAccessor.php on line 438 and defined in C:\Sifony\src\Sifo\SharedBundle\Entity\BlogMenu.php line 332

這是我的實體BlogMenu.php行332:

// ... 

* Set blogPage 
* 
* @param \Sifo\SharedBundle\Entity\BlogPage $blogPage 
* @return blogPage 
*/ 
public function setBlogPage(\Sifo\SharedBundle\Entity\BlogPage $blogPage) // Line 332 
{ 
    $this->blogPage = $blogPage; 

    return $this; 
} 

/** 
* Get blogPage 
* 
* @return \Sifo\SharedBundle\Entity\BlogPage 
*/ 
public function getBlogPage() 
{ 
    return $this->blogPage; 
} 

// ... 

updateAction在我的控制器是這樣的:

/** 
* Edits an existing BlogMenu entity. 
* 
*/ 
public function updateAction(Request $request, $id) 
{ 
    $user = $this->getUser(); 
    $em = $this->getDoctrine()->getManager(); 
    $entity = $em->getRepository('SifoSharedBundle:BlogMenu')->find($id); 

    if (!$entity) { 
     throw $this->createNotFoundException('Unable to find BlogMenu entity.'); 
    } 

    $entity->setOperator($user->getName()); 
    $form = $this->createEditForm($entity); 
    $form->handleRequest($request); 

    if ($form->isValid()) { 
     $em->flush(); 

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

    return $this->render('SifoAdminBundle:edit:layout.html.twig', array(
     'entity' => $entity, 
     'form' => $form->createView(), 
     'user' => $user, 
    )); 
} 

這是我的FormType:

<?php 

// ... 

    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder 
      ->add('blog_page', 'entity', array(
       'required' => false, 
       'empty_value' => 'admin.choice.choosePage', 
       'class' => 'Sifo\SharedBundle\Entity\BlogPage')) 

// ... 

如果需要,我會提供更多信息。感謝您的幫助。

回答

1

修改代碼以這種

public function setBlogPage(\Sifo\SharedBundle\Entity\BlogPage $blogPage = null) 
{ 
    $this->blogPage = $blogPage; 

    return $this; 
} 

正如我告訴你的評論,這是由於type hinting。類型提示用於檢查傳遞給函數的參數的類型(類;不是原始類型,您可以檢查this answer)。如果你想讓你的函數接受null類型,你應該指定它。

最好使用類型提示,因爲它「更安全」,不會導致「副作用」(如果可能)。讓我們考慮第三方庫或供應商:如果您使用第三方庫中的函數,您應該知道參數類型,如果嘗試傳遞錯誤的類型,「編譯器」(解析器)會通知您。

+0

非常感謝。這是工作很好:) – 2014-10-06 08:05:20

+0

是的,你明白了。 – 2014-10-06 08:14:50

0

我不確定這是否是解決此問題的好方法。我在我的實體中刪除了變量聲明作爲實體。

* Set blogPage 
* 
* @param \Sifo\SharedBundle\Entity\BlogPage $blogPage 
* @return blogPage 
*/ 
public function setBlogPage($blogPage) // Line 332 
{ 
    $this->blogPage = $blogPage; 

    return $this; 
} 

希望能幫助在這個問題上掙扎的人。

+0

這將解決問題,但它不是類型安全 – DonCallisto 2014-10-06 07:21:10

+0

@DonCallisto:你能建議一個安全的方法來做到這一點嗎? – 2014-10-06 07:55:36