如何在 Symfony 4 中通过 Ajax 加载和提交表单

How can I load and submit a form via Ajax in Symfony 4

我正在通过 Ajax 将表单加载到我的页面:

$('.table tbody').on( 'click', '.edit-item', function (e) {
  var id = $(this).attr("data-id");
  e.preventDefault();
  var $link = $(e.currentTarget);
  $.ajax({
    method:'POST',
    data: {
      "id": id
    },
    url: $link.attr('href')
  }).done(function(data){
    $('.form-output').html(data.output);

    $('#form_save').on( 'click', function (e) {
      e.preventDefault();
      var form = $(this).closest('form');
      var formData = form.serialize();
      alert("save button clicked");
      $.ajax({
        method:'POST',
        url:'{{ path('edit_form', { 'slug': page.slug }) }}',
        data: formData,
        success: function(data){

          alert("success");
        }
      });
    });

  });
});

Controller.php:

 /**
  * @Route("/pages/{slug}/edit", name="edit_form", methods={"POST", "GET"})
  */


  public function toggleArticleHeart($slug, Request $request){

    if($request->request->get('id')){

      $id = $request->request->get('id');
      $item = new User();

      $item= $this->getDoctrine()->getRepository(User::class)->find($id);
      $form = $this->createFormBuilder($item)
      ->add('username', TextType::class, array('attr' => array('class' => 'form-control')))
      ->add('email', EmailType::class, array('attr' => array('class' => 'form-control')))
      ->add('is_active', HiddenType::class)
      ->add('plainPassword', RepeatedType::class, array('type' => PasswordType::class,'invalid_message' => 'The password fields must match.','options' => array('attr' => array('class' => 'password-field')),'required' => false,'first_options'  => array('label' => 'Passwort', 'attr' => array('class' => 'form-control')),'second_options' => array('label' => 'Passwort wiederholen', 'attr' => array('class' => 'form-control')),))
      ->add('cancel', ButtonType::class, array('label' => 'Abbrechen','attr' => array('class' => 'cancel form-btn btn btn-default pull-right close_sidebar close_h')))
      ->add('save', SubmitType::class, array('label' => 'Speichern','attr' => array('id' => 'submit-my-beautiful-form','class' => 'form-btn btn btn-info pull-right','style' => 'margin-right:5px')))
      ->getForm();
      $form->handleRequest($request);


      $response = new JsonResponse(
        array(
          'message' => 'Success',
          'output' => $this->renderView('form.html.twig',
          array(
            'entity' => $item,
            'form' => $form->createView(),
          ))), 200);

          return $response;

        } else {

          $data = $request->request->get('data');
          $entityManager->persist($data);
          $entityManager = $data->getDoctrine()->getManager();
          $entityManager->flush();
          $response = new Response();
          $response->send();
        }
     }

我收到消息 "save button clicked" 但没有收到消息 "success"。

还有一个Ajax 500错误:

Uncaught PHP Exception ErrorException: "Notice: Undefined variable: entityManager"

您需要在您的控制器(即$entityManager = $this->getDoctrine()->getManager();)中定义并初始化$entityManger,然后再使用它,更改您的控制器如下:

/**
* @Route("/pages/{slug}/edit", name="edit_form", methods={"POST", "GET"})
*/

public function toggleArticleHeart($slug, Request $request){

   if($request->request->get('id')){

     $id = $request->request->get('id');
     $item = new User();

     $item= $this->getDoctrine()->getRepository(User::class)->find($id);
     $form = $this->createFormBuilder($item)
     ->add('username', TextType::class, array('attr' => array('class' => 'form-control')))
     ->add('email', EmailType::class, array('attr' => array('class' => 'form-control')))
     ->add('is_active', HiddenType::class)
     ->add('plainPassword', RepeatedType::class, array('type' => PasswordType::class,'invalid_message' => 'The password fields must match.','options' => array('attr' => array('class' => 'password-field')),'required' => false,'first_options'  => array('label' => 'Passwort', 'attr' => array('class' => 'form-control')),'second_options' => array('label' => 'Passwort wiederholen', 'attr' => array('class' => 'form-control')),))
     ->add('cancel', ButtonType::class, array('label' => 'Abbrechen','attr' => array('class' => 'cancel form-btn btn btn-default pull-right close_sidebar close_h')))
     ->add('save', SubmitType::class, array('label' => 'Speichern','attr' => array('id' => 'submit-my-beautiful-form','class' => 'form-btn btn btn-info pull-right','style' => 'margin-right:5px')))
     ->getForm();
     $form->handleRequest($request);

     $response = new JsonResponse(
     array(
         'message' => 'Success',
         'output' => $this->renderView('form.html.twig',
         array(
            'entity' => $item,
            'form' => $form->createView(),
         ))), 200);

      return $response;

    } else {

      $entityManager = $this->getDoctrine()->getManager();
      $data = $request->request->get('data');
      // Create Entity object and set it property with setter and then do persist on entity object 
      $entityManager->persist($data);
      $entityManager->flush();
      $response = new Response();
      $response->send();
    }
 }