【问题标题】:How can I save data in the database with a form that is loaded via Ajax in Symfony 4?如何在 Symfony 4 中使用通过 Ajax 加载的表单将数据保存在数据库中?
【发布时间】:2018-08-10 13:58:43
【问题描述】:

homepage.html.twig

<a class="load-form" href="{{ path('article_load_form', {slug:page.slug}) }}">Load my beautiful form</a>

<div  class="show-form">form will appear here</div>

  <script>
$( ".load-form" ).on( "click", function(e) {

        e.preventDefault();

        var $link = $(e.currentTarget);

        $.ajax({method:'POST', url: $link.attr('href')}).done(function(data){
          $('.show-form').html(data.output);

        });
      });
</script>

myController.php

 /**
  * @Route("/pages/{slug}/heart", name="article_load_form", methods={"POST"})
  */


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

        $id = 9;

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

            if($form->isSubmitted() && $form->isValid()) {
              $entityManager = $this->getDoctrine()->getManager();
              $entityManager->flush();
            }

          }

当我单击“加载我漂亮的表单”时,我的表单被加载,其中包含数据库中每个字段的所有数据。所以这工作正常。但是当我更改表单内的数据(例如用户名从“leo”到“alan”)并单击保存按钮时,数据库中没有存储任何数据(用户名仍然是“leo”)。

在分析器中,POST 参数是正确的。但是没有为此请求提交任何表单。

【问题讨论】:

  • 拜托,如果你告诉我为什么不投票,我会很高兴。因为我真的找不到解决办法。我发布了我的方法。没有错误消息,所以我不能发布任何错误。

标签: json ajax forms symfony doctrine


【解决方案1】:

该操作将在到达下一个块之前返回响应

    if($form->isSubmitted() && $form->isValid()) {
        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->flush();
    }

所以数据库中不会存储任何内容。

那么让我们看看你想做什么, 您尝试使用 ajax 获取美丽并将其放入您的加载表单,因此您首先需要使用 get 方法,方法:'GET',

之后,您需要使用其他 ajax 方法通过 post 将数据加载到服务器

$('#submit-my-beautiful-form').click(function(e){
        e.preventDefault();
        var form = $(this).closest('form');
        var formData = form.serialize(); 
        alert(formData);         
        $.ajax({
            method:'POST',
            url: $link.attr('href'),
            data: formData,
            success: function(data){
                alert(data);
            }
        });
})

ps:您的表单数据将被序列化并影响到 formData 变量,然后加载到服务器 ps:你需要为你的保存按钮添加一个id:

 ->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')))

ps:不要忘记持久化你的 $item 对象

$entityManager->persist($item);

【讨论】:

  • 谢谢。那么我可以做些什么来存储它呢?
  • 我试图在json响应块之前设置这个块。但这并没有解决问题
  • 你需要在刷新之前持久化你的对象,因为你刚刚实例化了它,$entityManager = $this->getDoctrine()->getManager(); $entityManager->persist($item); $entityManager->flush();
  • 谢谢!我测试了$entityManager-&gt;persist($item); 但仍然没有存储数据
  • 没有为此请求提交任何表单。
猜你喜欢
  • 1970-01-01
  • 2019-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-30
  • 1970-01-01
相关资源
最近更新 更多