Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

94
Views
crud ajax jquery symfony3 wont work

Problem: How do I validate the form and return the validation messages in modal box without refreshing the page.

I just started learning Symfony 3 and I got trouble adding data using AJAX. I know how to include the template form inside of the modal box but I don't know how to show the error messages of $form->isValid() inside the modal and persist it.

new.html.twig

UPDATE: I can now call the method action in Controller. But when I validate the form I haven't received any validation error inside modal box.

<script>
    $(function () {
        $('.withdropdown').dropdown();
        $('.add-company-launch').modal();

        $('#company-form').submit(function(e) {

            var formUrl = "{{ path('monteal_backend_company_ajax') }}";
            var formData = new FormData(this)

            $.ajax({
                url: formUrl,
                type: 'POST',
                data:  formData,
                 contentType: false,
                 cache: false,
                processData: false,
                success: function(data, textStatus, jqXHR)
                {
                    if(data['status'] === 'success'){
                        alert('success');
                    } else {
                        $('#add-company').html(data['html']);
                    }
                },
                error: function(jqXHR, textStatus, errorThrown)
                {
                }
            });

            e.preventDefault();
        });
    })
</script>

{% endblock %}

CompanyController.php

UPDATE: I have create two methods for AJAX, 1. Method to handle a form. 2. AjaxHandler.

   public function newAction() {

        $company = new Company();

        $form = $this->createForm(CompanyForm::class, $company);

        return $this->render('Admin/Backend/Company/new.html.twig', array(
            'form'=>$form->createView()
        ));
    }

    public function ajaxAction(Request $request) {

        if (!$request->isXmlHttpRequest()) {
            return new JsonResponse(array('message' => 'You can access this only using Ajax!'), 400);
        }

        $company = new Company();
        $form = $this->createForm(CompanyForm::class, $company);
        $form->handleRequest($request);

        if ($form->isValid()) {

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

            return new JsonResponse(array(
                'status' => 'success'), 200
            );
        }

        $html = $this->renderView("Admin/Backend/Company/new.html.twig", array(
            'form' => $form->createView())
        );

        return new JsonResponse(['status' => 'error', 'html' => $html]);
    }
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

1 - In your newAction, just create the form and pass the view (createView) to your template.

2 - write a ajaxFormHandlerAction and here create the form, handle it, validate it, render a view in a variable : $html = $this->renderView('yourTemplate.html.twig', array($form->createView())); Edit: of course your ajax must post the form to your newly ajax url... END Edit

3 - if it is'nt validated Return a JsonResponse(array('html' => $html, 'status' => 'error')); if validated Return a JsonResponse(array('status' => 'success'));

4 - In your ajax success callback, render the newly form if status error.. if status success, redirect or whatever

Hope this help

Edit :

something like this for your controler :

    use Symfony\Component\HttpFoundation\JsonResponse;
    public function ajaxFormHandlerAction(Request $request) 
    {
        $company = getYourCompany(); //get it from db?
        $form = $this->createForm(CompanyForm::class, $company));
        $form ->handleRequest($request);
        if($form ->isValid()){
             //do whatever you want, maybe persist, flush()
             return new JsonResponse(array(
                'status' => 'success'));
        }
        $html = $this->renderView("yourModalTemplate.html.twig", array('form' => $form->createView()));
        return new JsonResponse(['status' => 'error', 'html' => $html]);
     }

And in your success ajax callback:

success: function(data, textStatus, jqXHR)
{
    if(data['status'] === 'success'){
        alert('success');
        // maybe redirect the user ???
    }else if(data['status' === 'error']){
        $('#idOfYourModal').html(data['html']); //assuming you use jquery, or translate to javascript
    }
},

You have to create a twig template with only the modal inside...

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!