【问题标题】:Symfony2: send form and other variables with ajaxSymfony2:使用 ajax 发送表单和其他变量
【发布时间】:2015-01-06 17:10:18
【问题描述】:

我正在使用 Symfony 2.5.3 版,我正在尝试使用 Ajax 提交表单。 所以,在我的控制器中,我有

  $form = $this->createForm(
      new MyFormType(), 
      $formvariable
  );

  $form->handleRequest( $request );

  if ($form->isValid()) {
      // do stuff
  } else {
      // other stuff
  } 

而我的 jQuery 脚本可能与此类似:

    formdata = $('form[name=MyFormTypeForm]').serialize();

    $.ajax({
        type: "POST",
        url: // my url,
        data: formdata ,
        async: true,
        dataType: "json",
        success: function(response) 
        {
            // stuff here
        },
        error: function(XMLHttpRequest, textStatus, errorThrown)
        {
            // stuff there
        },
    });

这可以正常工作,但不幸的是,我必须将其他变量与表单的字段一起发送。
我想在我的 jQuery 中做的是这样的:

    formdata = $('form[name=MyFormTypeForm]').serialize();

    value      = { 
                  myvar1   : data1    ,
                  myvar2   : data2    ,
                  formdata : formdata ,
                };

    $.ajax({
        type: "POST",
        url: // my url,
        data: value ,
        async: true,
        dataType: "json",
        success: function(response) 
        {
            // stuff here
        },
        error: function(XMLHttpRequest, textStatus, errorThrown)
        {
            // stuff there
        },
    });

但是这样$form->isValid()在控制器内部总是返回false。

有没有办法解决这个问题?
提前谢谢你

阿尔伯托

编辑: 添加一些额外的细节,以回应 cmets:

我无法在我的表单中添加一些额外的字段,因为额外的变量用于生成表单本身。

控制器的更多细节:

    $em = $this->getDoctrine()->getManager();

      $action = $request->request->get('action',   null);
      $myentid = $request->request->get('myentid',   null);

      // Here I determine if I have to create a form for a new entity or an 
      // entity already present in the database
      if ( empty($myentid) )
      {
          // New entity
          $formvariable = new MyEntity();
      } else {
          // Retrieve entity from database
          $formvariable = $this->getDoctrine()->getManager()
              ->getRepository('MyBundle:MyEntity')
              ->find($myentid);
      }

      $form = $this->createForm(
          new MyFormType(), 
          $formvariable
      );

      // I am requesting a new form: render the form and send to page
      if ($action == "newform")
      {
          $response["code"] = $this->render('MyBundle:Controller:mytwigview.html.twig', array( 
              'form' => $form->createView(), 
              ))->getContent();
          return new Response(json_encode($response));

      }

      // The form has already been filled: save
      if ($action == "save")
      {
          $form->handleRequest( $request);

          if ($form->isValid()) {
              $em->flush();
          } else {
              echo "Errors: ".$form->getErrors();
          }
      }

// And here I return the save confirmation

【问题讨论】:

  • 如何将额外的数据作为隐藏输入添加到表单中?
  • 不幸的是,这是不可能的。我需要这些额外的数据来有效地生成与表单数据相关联的表单。
  • Wenn 额外的数据用于生成表单......而不是应该可以将其注入表单本身......你是如何生成它的?你能把这个添加到你的问题中吗?
  • 编辑了我原来的问题以满足您的要求。
  • 看来您正在尝试合并新操作和编辑操作,对吧?

标签: jquery ajax forms symfony


【解决方案1】:

我使用以下内容通过 Ajax 一次提交两个表单。这也是您问题的答案:

$.ajax({
    type: "POST",
    url: Routing.generate('ajax_report_processing_create_pdf'),
    data: $reportMainWrapper.find('form[name="report"]').serialize() + '&' +
    $reportProcessingForm.find('form').serialize(),
    dataType: "json"
})
    .done(function (data) {
        console.log('done');
        console.log(data);
    })
    .fail(function (jqXHR, textStatus, errorThrown) {
        console.log('fail');
        console.log(jqXHR);
    })
    .always(function () {
        console.log('always');
    });

如您所见,您可以使用:

data: 'myvar1=' + data1 + '&' + 'myvar2=' + data2 + '&' + formdata,

如你所见,我没有'formdata=' + formdata,。那是因为你的变量formdata 已经包含了这样的键值数据:

form[yourinput1]  = 'string1'
form[yourinput2]  = 'string2'

因此,您现在可以在控制器中简单地执行$form->handleRequest($request);,它会立即生效。

【讨论】:

    【解决方案2】:

    我建议控制器应该看起来像这样:

    /**
     * @Route("/myentity/{myentid}")
     */
    public function newAndEditAction(Request $request, $myentid = null)
    {
        $em = $this->getDoctrine()->getManager();
    
        // Here I determine if I have to create a form for a new entity or an 
        // entity already present in the database
        if ($myentid)
        {
            // Retrieve entity from database
            $formvariable = $this->getDoctrine()->getManager()
                ->getRepository('MyBundle:MyEntity')
                ->find($myentid);
        } else {
            // New entity
            $formvariable = new MyEntity();
        }
    
        $form = $this->createForm(
            new MyFormType(),
            $formvariable
        );
    
        if ($request->getMethod() == 'POST') { // save
            $form->handleRequest($request);
    
            if ($form->isValid()) {
                $em->flush();
                // return some response
                return Response(...);
            }
        } else { // edit and new
            return new Response($this->render('MyBundle:Controller:mytwigview.html.twig', array(
                'form' => $form->createView(),
            ))->getContent());
        }
    }
    

    我将此操作的 id 参数设为可选,并根据 id 参数和请求方法决定是否保存/更新和显示新表单或编辑表单。

    【讨论】:

    • 这似乎没有回答如何处理'values'数组中提交的表单数据?
    猜你喜欢
    • 1970-01-01
    • 2017-11-01
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    • 2017-08-17
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    相关资源
    最近更新 更多