如何用Axios提交Symfony 4表单并实现后端校验?
实现Axios提交Symfony表单并触发后端校验逻辑
要让后端的if($form->isSubmitted() && $form->isValid())检测到表单提交,你需要调整前端的表单提交逻辑和后端的请求处理逻辑,具体步骤如下:
一、修改前端代码:实现表单数据提交
在Swal的preConfirm函数中,我们需要获取模态框内的表单数据,通过Axios发送POST请求到后端路由,同时处理成功/失败的响应:
{# template.html.twig #} productId = {{product.id}}; var url = Routing.generate("stripe_admin_product_update_form", {id: productId}); axios.get(url) .then(function(response){ var form = response.data.form; Swal.fire({ title: "Modifier ?", html: form, icon: "question", showCancelButton: true, allowOutsideClick: () => !Swal.isLoading(), preConfirm: function() { // 获取Swal模态框中的表单元素 const formElement = Swal.getHtmlContainer().querySelector('form'); // 创建FormData对象,自动包含表单所有字段(包括Symfony的CSRF令牌) const formData = new FormData(formElement); // 发送POST请求提交表单 return axios.post(url, formData) .then(response => { if (response.data.success) { // 提交成功:返回true让Swal自动关闭弹窗 // 这里可以添加额外操作,比如刷新页面或提示成功信息 Swal.fire("Succès!", response.data.message, "success"); return true; } else { // 表单验证失败:抛出错误,让Swal更新显示带错误的表单 throw new Error(response.data.form); } }) .catch(error => { // 更新Swal的内容为后端返回的带错误的表单 Swal.update({ html: error.message }); // 返回false阻止Swal关闭弹窗,让用户修改表单 return false; }); } }); });
二、调整后端代码:支持POST请求并处理表单提交
需要修改路由允许POST请求,并在控制器中处理表单提交逻辑:
// controller.php use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\JsonResponse; /** * @Route("/admin/stripe/product/{id}/update/form", name="stripe_admin_product_update_form", options={"expose"=true}, methods={"GET", "POST"}) */ public function getUpdateProductForm(Request $request, StripeProduct $product) { $form = $this->createFormBuilder($product) ->add("name") ->add("unitLabel") ->add("bankStatementLabel") ->getForm(); // 处理表单提交(仅当请求为POST时生效) $form->handleRequest($request); if($form->isSubmitted() && $form->isValid()) { // 这里写你的业务逻辑,比如保存数据到数据库 $entityManager = $this->getDoctrine()->getManager(); $entityManager->flush(); // 返回成功响应 return new JsonResponse([ "code" => 200, "success" => true, "message" => "Produit modifié avec succès !" ]); } // 如果是GET请求,或者表单验证失败,返回带错误的表单HTML $response = [ "code" => $form->isSubmitted() ? 400 : 200, "success" => false, "form" => $this->render("stripe_admin/product/_form_edit.html.twig", [ "form" => $form->createView(), ])->getContent() ]; return new JsonResponse($response); }
三、关键细节说明
- CSRF令牌处理:
FormData会自动包含Symfony表单生成的CSRF令牌字段(默认名为_token),无需手动添加,确保了表单的安全性。 - 请求头处理:Axios发送
FormData时会自动设置正确的Content-Type: multipart/form-data头,无需手动指定(手动指定可能会丢失boundary参数,导致后端无法解析表单)。 - 错误反馈:当表单验证失败时,后端会重新渲染带有错误提示的表单HTML,前端通过
Swal.update更新模态框内容,用户可以直接看到错误并修改。 - Swal流程控制:
preConfirm返回Promise,Swal会等待请求完成后再决定是否关闭弹窗——成功则关闭,失败则保留弹窗让用户继续修改。
内容的提问来源于stack exchange,提问作者eronn
相关产品推荐
相关产品推荐

