我在向相关实体提交来自时遇到问题。提交表单时收到以下错误消息:
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 :(得分: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找到一个项目时,您没有获得项目,因此当您尝试设置项目时,您将传递空值。