1

提交与相关实体的来自时遇到问题。提交表单时收到以下错误消息:

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()));

我不知道如何解决这个问题。谢谢你的帮助!

4

1 回答 1

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 查找一个项目时,您没有得到一个项目,因此当您尝试设置项目时,您正在传递一个空值。

于 2012-06-12T09:37:55.293 回答