2012-06-12 60 views
1

從相關實體提交一個問題時出現問題。我得到提交表單時出現以下錯誤信息:Symfony2表單提交相關實體錯誤

Catchable Fatal Error: Argument 1 passed to 
My\ReportBundle\Entity\Clearance::setProjectProject() must be an instance of 
My\ReportBundle\Entity\Project, null given, called in 
/var/www/Symfony/src/My/ReportBundle/Controller/DefaultController.php on line 85 and 
defined in /var/www/Symfony/src/My/ReportBundle/Entity/Clearance.php line 272 

表單生成器的代碼如下所示:

namespace My\ReportBundle\Form; 

use Symfony\Component\Form\AbstractType; 
use Symfony\Component\Form\FormBuilder; 

class ClearanceType extends AbstractType 
{ 


public function buildForm(FormBuilder $builder, array $options) 
{ 
    $builder 
     // Fields from the clearance entity removed ... 
     // here is the problematic entry 
     ->add('projectProject','entity', 
     array('class'=>'My\ReportBundle\Entity\Project', 'property'=>'projectId')) 
     ; 
    } 

     public function getName() 
    { 
     return 'my_reportbundle_clearancetype'; 
     } 

而控制器包含以下代碼:

 public function newclearanceAction() 
    { 
    $request = $this->getRequest(); 
    $id = $request->query->get('projectId'); 
    $em = $this->getDoctrine()->getEntityManager(); 
    $project = $em->getRepository("MyReportBundle:Project")->find($id); 

    $clearance = new Clearance(); 
    $clearance->setProjectProject($project); 
    $form = $this->createForm(new ClearanceType(), $clearance); 

    if ($request->getMethod() == 'POST'){ 
      $form->bindRequest($request); 

      if($form->isValid()) { 
        $em = $this->getDoctrine()->getEntityManager(); 
        $em->persist($clearance); 
        $em->flush(); 
        return $this-> 
        redirect($this->generateUrl('MyReportBundle_project_list')); 
      } 
     } 
     return $this->render('MyReportBundle:Clearance:new.html.twig', 
       array('form'=>$form->createView())); 

我不沒有任何想法如何解決這個問題。 感謝您的幫助!

回答

0

當您發佈表單時,是否在查詢字符串中設置了projectId?

如果不嘗試:

$request = $this->getRequest(); 

$em = $this->getDoctrine()->getEntityManager(); 
$clearance = new Clearance(); 

if($request->getMethod() != 'POST'){ 
    $id = $request->query->get('projectId'); 
    $project = $em->getRepository("MyReportBundle:Project")->find($id); 
    $clearance->setProjectProject($project); 
} 
$form = $this->createForm(new ClearanceType(), $clearance); 

的錯誤來了,因爲你沒有得到一個項目,當你試圖找到一個通過ID,因此,當您嘗試並設置項目要傳遞一個空值通過。

+0

這是我的問題!非常感謝 :-) – mbs