Symfony中Answer实体创建表单报错及关联Question路由配置问题
问题解决方案
1 新建答案异常修复
你遇到的新建异常是两个原因导致的:
- 控制器create方法的参数中多余注入了
Answer $answer,但路由没有对应参数,Symfony参数转换器无法匹配会抛出异常,且你后续手动实例化Answer覆盖了该参数,直接删除该参数即可。 - Answer实体的
question字段配置了非空约束,但你提交表单时没有给Answer实例关联对应的Question,数据库插入时报非空约束错误。
2 绑定问题提交回答的路由&逻辑改造
步骤1:修改AnswerController的create方法
调整路由加入问题ID参数,利用Symfony参数转换器自动获取Question实例,再关联到Answer:
/** * Create action. * * @param \Symfony\Component\HttpFoundation\Request $request HTTP request * @param \App\Repository\AnswerRepository $answerRepository Answer repository * @param \App\Entity\Question $question 自动匹配路由中的questionId获取问题实体 * * @return \Symfony\Component\HttpFoundation\Response HTTP response * * @throws \Doctrine\ORM\ORMException * @throws \Doctrine\ORM\OptimisticLockException * * @Route( * "/create/{questionId}", * methods={"GET", "POST"}, * name="answer_create", * ) */ public function create(Request $request, AnswerRepository $answerRepository, Question $question): Response { $answer = new Answer(); // 预先给Answer关联当前问题 $answer->setQuestion($question); $form = $this->createForm(AnswerType::class, $answer); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $answerRepository->save($answer); $this->addFlash('success', 'answer_created_successfully'); // 提交成功跳转回当前问题详情页,注意替换为你自己的问题详情路由名 return $this->redirectToRoute('question_show', ['questionId' => $question->getId()]); } return $this->render( 'answer/create.html.twig', ['form' => $form->createView(), 'question' => $question] ); }
步骤2:修改问题详情页模板
在你的问题详情页(对应路由/question/{questionid}的模板文件)中,把回答表单的提交路径指向带当前问题ID的路由即可:
{# 假设模板中当前问题实例变量叫question #} {{ form_start(form, {'action': path('answer_create', {'questionId': question.id})}) }} {{ form_widget(form) }} <button type="submit">提交回答</button> {{ form_end(form) }}
可选优化
你的Answer实体中Question关联配置inversedBy="answer",如果Question实体中对应的一对多属性是$answers(一个问题对应多个答案),建议修改为inversedBy="answers",避免后续关联查询出错。
内容的提问来源于stack exchange,提问作者Harizu
相关产品推荐
相关产品推荐

