简体   繁体   中英

How to show inline error Messages from server side validation with AJAX

I want to show inline error messages from my Symfony2 Backend without reloading the page.

I thought that I can replace the existing form in the HTML with the validated form with the error messages which the backend returns via AJAX.

But I can't identify the errors in my code.

I'm new on the whole web developing so please don't blame me when there are some beginner errors.

I render a form from an entity and a form type.

contactEntity

contactType

My form looks something like this:

  <form id="contact-form"
        action="{{ path('sendContact') }}"
        method="post" {{ form_enctype(form) }}>
    <h2 class="text-center">Kontaktieren Sie uns</h2>


    {{ form_row(form.name, {'label': 'Name'}) }}
    {{ form_row(form.email, {'label': 'Email'}) }}
    {{ form_row(form.subject, {'label': 'Betreff'}) }}
    {{ form_row(form.message, {'label': 'Nachricht'}) }}

    {{ form_rest(form) }}

    <div class="form-group">
      <div class="col-sm-offset-2 col-sm-10">
        <button style="width:100%"
                id="contact-form-button"
                type="submit"
                class="btn btn-default">
          Senden
        </button>

      </div>
    </div>
  </form>

My ContactController:

<?php

namespace piano\PageBundle\Controller;

use piano\PageBundle\Entity\Contact;
use piano\PageBundle\Form\ContactType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;


class ContactController extends Controller
{
  /**
   * @Route("/kontakt", name="contact")
   */
  public function indexAction()
  {
    $contact = new Contact();
    $form = $this->createForm(new ContactType(), $contact);


    return $this->render('pianoPageBundle:Contact:show.html.twig', array(
      'form' => $form->createView()
    ));
  }

  /**
   * @Route("/kontakt/senden", name="sendContact")
   */
  public function sendAction(Request $request)
  {
    $contact = new Contact();
    $form = $this->createForm(new ContactType(), $contact);
    $form->handleRequest($request);

    if ($form->isValid()) {

      $mailer = $this->get('mailer');
      $message = $mailer->createMessage()
        ->setSubject($form->get('subject'))
        ->setFrom('email@example.com')
        ->setTo('some@mail.com')
        ->setBody(
          $this->renderView(
            'pianoPageBundle:Emails:contact.html.twig',
            array('form' => $form)
          ),
          'text/html'
        );
      $mailer->send($message);
      return new JsonResponse(array(
        'success' => true
      ));
    } else {
      return new Response($form->createView(), 201, array(
          'data' => $form->createView(),
          'Content-Type' => 'application/x-www-form-urlencoded')
      );
    }
  }
}

And this is my js:

$("#contact-form").submit(function (e) {
    e.preventDefault();

    $.ajax({
        url: $(this).attr("action"),
        dataType: 'text',
        method: $(this).attr("method"),
        contentType: 'application/x-www-form-urlencoded',
        data: $(this).serialize(),
        success: function (data) {
            //send mail
        },
        error: function (response) {
            $("#contact-form").replaceWith(response.data);
        }
    });
});

My problem is, that i get the error message:

The Response content must be a string or object implementing __toString(), &quot;object&quot; given. (500 Internal Server Error)

I tried many hours fix the problem but I don't know the right response type for replacing the whole form.

You're using the wrong Request class. You should use:

use Symfony\Component\HttpFoundation\Request;

The rest seems to look ok.

Answer to your next question:

You should change this:

return new Response($form->createView(), 201, array(
          'data' => $form->createView(),
          'Content-Type' => 'application/x-www-form-urlencoded')
      );

to:

return $this->render('formview.html.twig', array(
      'form' => $form->createView()
    ));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM