dongtuan1980 2018-08-13 16:07
浏览 105
已采纳

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

I am loading a form via Ajax to my page:

$('.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();
        }
     }

I get the message "save button clicked" but not the message "success".

And there is also an Ajax 500 Error:

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

  • 写回答

1条回答 默认 最新

  • douzhao4071 2018-08-13 16:24
    关注

    You need to define and initialize $entityManger in your controller (i.e. $entityManager = $this->getDoctrine()->getManager();) before using it, change your controller as follows:

    /**
    * @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();
        }
     }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 收益高的广告联盟有哪些
  • ¥15 Android Studio webview 的使用问题, 播放器横屏全屏
  • ¥15 删掉jdk后重新下载,Java web所需要的eclipse无法使用
  • ¥15 uniapp正式环境中通过webapi将本地数据推送到设备出现的跨域问题
  • ¥15 xui建立节点,显示错误
  • ¥15 关于#单片机#的问题:开始、复位、十进制的功能可以实现,但是切换八进制的功能无法实现(按下按键也没有效果),把初始状态调成八进制,也是八进制可以实现但是切换到十进制不行(相关搜索:汇编语言|计数器)
  • ¥15 VINS-Mono或Fusion中feature_manager中estimated_depth是特征的深度还是逆深度?
  • ¥15 谷歌浏览器如何备份抖音网页数据
  • ¥15 分别有什么商家下面需要非常多的骑手为它工作?
  • ¥15 开机logo到Qt应用起来会黑屏将近两秒时间