Form Validation in symfony from ajax call

前端 未结 3 2006
小蘑菇
小蘑菇 2020-12-16 16:02

I need to store data from a form with symfony through an ajax call me not to update the browser. Also I need you in case of errors in the fields can somehow get them in resp

3条回答
  •  暖寄归人
    2020-12-16 16:24

    With symfony 3 and the error validator you can parse your Ajax request like this:

     /**
         * Create new student (ajax call)
         * @Method("POST")
         * @Route("/student/create", name"student_create")
         * @param Request $request
         * @return JsonResponse
         */
        public function createAction(Request $request)
        {
    
            $student = new Student();
            $form = $this->createForm(CreateStudentType::class, $student);
            $form->handleRequest($request);
            $errors = array();
    
            if ($form->isSubmitted()) {
                $validator = $this->get('validator');
                $errorsValidator = $validator->validate($student);
    
                foreach ($errorsValidator as $error) {
                    array_push($errors, $error->getMessage());
                }
    
    
                if (count($errors) == 0) {
                    $em = $this->getDoctrine()->getManager();
                    $em->persist($student);
                    $em->flush();
    
                    return new JsonResponse(array(
                        'code' => 200,
                        'message' => 'student toegevoegd',
                        'errors' => array('errors' => array(''))),
                        200);
                }
    
            }
    
            return new JsonResponse(array(
                'code' => 400,
                'message' => 'error',
                'errors' => array('errors' => $errors)),
                400);
        }
    

    And jquery ajax

    $("#createForm").submit(function(e) {
    
            e.preventDefault();
            var formSerialize = $(this).serialize();
    
            var url = location.origin + '/web/app_dev.php/student/create';
            $.ajax({
                type: "POST",
                url: url,
                data: formSerialize,
                success: function (result) {
                    console.log(result);
                    if (result.code === 200) {
                        // refresh current url to see student
                    } else {
    
                    }
                }
            });
        });
    

提交回复
热议问题