简体   繁体   English

如何显示来自AJAX服务器端验证的内联错误消息

[英]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. 我想在不重新加载页面的情况下显示来自我的Symfony2后端的内联错误消息。

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. 我以为我可以用后端通过AJAX返回的错误消息将HTML表单中的现有表单替换为经过验证的表单。

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 contactEntity

contactType 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: 我的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: 这是我的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. 您使用了错误的Request类。 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()
    ));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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