【问题标题】:Render form with errors via AJAX通过 AJAX 呈现带有错误的表单
【发布时间】:2014-05-14 01:34:20
【问题描述】:

我有一个名为“myAction”的操作,用于呈现我的项目的主页。此视图(页面)是 2 列布局,左侧有一个表,其中包含数据库中的所有项目。

在右侧,我根据具体情况呈现项目简历或新项目表格。

当用户点击“新建项目”按钮时,表单通过load() jQuery 函数呈现。因此,当表单被验证时,项目被保存并且您的简历被呈现在布局的右侧(删除表单),但是当表单无效时,我希望呈现有错误的表单。

所有表单请求都发送到newAction()方法控制器。

AJAX 请求是:

$.ajax({
   url: $form.attr('action'),
   type: $form.attr('method'),
   dataType: 'json',
   data: $form.serialize(),
   success: function(response){
      var object = JSON.parse(response);
      if(object.success){
         $("#ProjectList").load(Routing.generate('project_my'));
         fn_render_resumen(object.message);
      }else{
         // The form is invalid.
      }
   }
});

ProjectController 中的 newAction 是:

public function newAction(Request $request){
   $project = new Project();
   $form = $this->createForm(new ProjectType(), $project);

   if($request->isMethod('POST')){
      $form->bind($request);
      $response = array();

      if($form->isValid()){
         // Persist in the database...
         $response['success'] = true;
         $response['message'] = $project->getSlug();
      }else{
         // Here need send the form with errors to the view.
      }
      return new JsonResponse(json_encode($response));
   }
   return $this->render('aView.html.twig',Array('form' => $form->createView()));
}

那么,有什么想法吗?谢谢!

【问题讨论】:

    标签: ajax forms symfony


    【解决方案1】:

    首先你不需要将json_encode的数据传递给JsonResponse;只需这样做:

    return new JsonResponse($response);
    

    试试这个:

    if($form->isValid()){
        // Persist in the database...
        $response['success'] = true;
        $response['message'] = $project->getSlug();
    }else{
        $formHtml = $this->container
            ->get('templating')
            ->render('aViewForm.html.twig',Array('form' => $form->createView()));
        $response['success'] = false;
        $response['form'] = $formHtml;
    }
    return new JsonResponse($response);
    

    aViewForm.html.twig 是一个仅呈现表单的模板。例如,它可能看起来像这样:

    {{ form }}
    

    您将拥有完整的 HTML 代码(有错误)。像这样的:

    {"success":false,"form":"\u003Cform\u003E...\u003C\/form\u003E"}
    

    然后你可以在JS脚本中处理它。

    【讨论】:

      猜你喜欢
      • 2014-02-10
      • 2013-06-02
      • 1970-01-01
      • 2012-05-22
      • 1970-01-01
      • 1970-01-01
      • 2013-05-11
      • 2012-05-26
      • 1970-01-01
      相关资源
      最近更新 更多