【问题标题】:Symfony2.7 form not validSymfony2.7 表单无效
【发布时间】:2015-09-11 08:42:11
【问题描述】:

我正在使用 Symfony 2.7 开发博客。我有一个 ArticleBundle 和一个 CommentBundle。我的实体文章和评论通过多对一关系链接。

当我尝试发送评论时,它失败了。 $form->isValid() 方法返回 false。

这里,我的添加方法来发送评论:

public function addAction(Article $article, Request $request){
    $comment = new Comment();

    $form = $this->createForm(new CommentType(), $comment);
    $form->handleRequest($request);

    if($form->isValid()){
        $comment->setArticle($article);

        $em = $this->getDoctrine()->getManager();
        $em->persist($comment);
        $em->flush();

        return $this->redirect($this->generateUrl('esgi_article_view', array(
            'id' => $article->getId()
        )));
    } else{
        return $this->render('ESGICommentBundle:Comment:add.html.twig', array(
            'form' => $form->createView(),
            'article' => $article
        ));
    }
}

我的评论表单是这样包含在文章视图中的:

{{ render(controller("ESGICommentBundle:Comment:add", { 'id' : article.id })) }}

这里是我的表格:

{{ form_start(form) }}
<div class="form-group">
    <div class="row">
        <div class="col-xs-12 col-sm-6 col-md-8">
            {{ form_label(form.author, "Auteur") }}
            {{ form_widget(form.author, { 'attr' : { 'class' : 'form-control' } }) }}
            {{ form_errors(form.author) }}
        </div>
    </div>

    <div class="row">
        <div class="col-xs-12 col-sm-6 col-md-8">
            {{ form_label(form.email, "Email (optionnel)") }}
            {{ form_widget(form.email, { 'attr' : { 'class' : 'form-control' } }) }}
            {{ form_errors(form.email) }}
        </div>
    </div>

    <div class="row">
        <div class="col-xs-12 col-sm-6 col-md-8">
            {{ form_label(form.content, "Commentaire") }}
            {{ form_widget(form.content, { 'attr' : { 'class' : 'form-control' } }) }}
            {{ form_errors(form.content) }}
        </div>
    </div>
</div>

<button class="btn btn-success" type="submit">Poster</button>
{{ form_end(form) }} 

谢谢,祝你有美好的一天!

【问题讨论】:

  • 可能您忘记在表单中添加操作,如果您在不同的 url 上呈现此表单,则必须设置该操作。
  • 我在发帖前试过了,但没用。
  • @L.Baptiste 添加var_dump($form-&gt;getErrors(true))dump($form-&gt;getErrors(true)) ` 如果安装了 DebuggerBundle),然后在$form-&gt;handleRequest($request); 之后添加die();
  • @L.Baptiste else 部分在您的代码中是多余的,您可以在 if 语句之外返回第二个 return 语句..
  • getErrors 返回一个空数组。

标签: symfony twig symfony-2.7


【解决方案1】:

如果您提交表单,您应该在分析器栏中看到所有错误(有一个表单图标,您可以点击查看提交表单中的错误)

【讨论】:

  • 您好,Profiler 说:“此表单未提交。” :O ?
  • 尝试渲染整个表单 {{ form(form) }} 看看是否有区别
  • 我收到了同样的信息,表单没有提交
  • 检查
    标签是否有正确的动作和方法
猜你喜欢
  • 2016-01-12
  • 1970-01-01
  • 2013-09-14
  • 2020-04-21
  • 1970-01-01
  • 1970-01-01
  • 2020-12-05
  • 1970-01-01
相关资源
最近更新 更多