php - 多种形式包括symfony(同一页面)

标签 php symfony

我在使用多表单 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/

相关文章:

PHP 5.1.6 上的 PHP 变量到 JSON

php - 如果 PHP 中的数据库的 foreach 循环没有返回任何行怎么办?

symfony - 驱动程序 : SQLSTATE[HY000] [1045] Access denied for user 'db_user' @'localhost' (using password: YES) 发生异常

php - Symfony 2 - 从控制台命令调用 Controller 方法

symfony - 在 Symfony 2 控制台命令中获取服务容器给出 "getKernel() on a non-object"

PHP $_POST,它连接到表单的哪一部分?

php - 如何获取尊重用户时区的日期和时间

php - 调用未定义的方法 Illuminate\Database\Query\Builder::notify() Laravel 5.4

php - Symfony Forms 扩展 FormBuilder

mysql - 访问 twig 中数组的单个元素