我在使用多表单 symfony(包括)时遇到问题。
我在同一个页面中有多篇文章,用户可以为每篇文章添加评论。我想显示表单添加评论。
我的问题是:当我提交评论添加表单时,Symfony 没有将信息保存在数据库中(没有错误消息)。
我试图添加一个类来更改我的表单的名称,但它是一样的。
我在 Controller 中的表单操作(由每篇文章的 Twig View 调用)
public function formAction($post_id, Request $request) {
$user = $this->getUser();
$em = $this->getDoctrine()->getManager();
$post = $em->getRepository('AppBundle:Post')->find($post_id);
$comment = new Comment();
$comment -> setPost($post);
$comment -> setAuthor($user);
$form_comment = $this->createForm(CommentType::class, $comment);
$form_comment->handleRequest($request);
if ($form_comment->isSubmitted()) {
$em = $this->getDoctrine()->getManager();
$em->persist($comment);
$em->flush();
$request->getSession()->getFlashBag()->add('msg_success', 'Votre contribution a bien été ajoutée');
}
return $this->render('account/form-comment.html.twig', array(
'form_comment' => $form_comment->createView(),
'post_id' => $post_id
));
}
获取表单类型中的名称(用于唯一标识)
public function getName() {
return self::NAME . '_' . uniqid();
}
最佳答案
如果我没记错的话,问题出在 getName()
方法和 uniqid()
。
您 Controller 中的名称与您的 Twig 不同,因此您的表单无效。
我想您想更改表单的名称以在您的 View 中具有不同的 ID,如果是这种情况,您可以像这样在表单中放置一个 ID:
{{ form_start(form_comment, {'attr': {'id' : uniqvalue}}) }}
uniqvalue
可能是一个计数器
关于php - 多种形式包括symfony(同一页面),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34449670/