【问题标题】:Symfony2 get a form with AJAXSymfony2 使用 AJAX 获取表单
【发布时间】:2014-11-21 09:46:02
【问题描述】:

我有一个客户列表,对于每个客户,我都有一个按钮来显示客户的编辑表单。 我希望当我点击这个按钮时,一个函数 ajax 显示点击的特定客户的编辑表单。

我不知道如何将表单呈现到使用 AJAX 执行的操作(控制器)中。

这是我在控制器中创建表单的方式:

public function editAction($id)
    {
        if ($this->container->get('request')->isXmlHttpRequest()) {
            $em = $this->getDoctrine()->getManager();

            $entity = $em->getRepository('ApplicationClientBundle:Client')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Client entity.');
            }

            $editForm = $this->createEditForm($entity);

            $answer =$this->container->get('templating')->renderResponse('ApplicationClientBundle:Client:index.html.twig', array(
                'editForm' => $editForm->createView(),
            ));

            $response = new Response(json_encode(array('editForm'=> $answer)));
            $response->headers->set('Content-type', 'application/json; charset=utf-8');
            return $response;
        }



    }

但是响应json是空的。

我可以在控制器和 index.html.twig 中做什么来显示表单?

编辑:

index.html.twig,我有:

{% block body %}
<div class="content-action">
    <div class="col-xs-12 col-sm-6 col-md-6">
        <p><span>Raison Sociale :</span><span id="raison_sociale" onclick="functionClick(this)">raison sociale</span></p>
        <p><span>Adresse :</span><span id="adresse"> Avenue Majida Boulila imm.....</span><p>
        <p><span>M.F. :</span><span id="matriculeFiscale"> 0000000 PES 000</span></p>
        <p><span>C.P. :</span><span id="codePostal"> 3027</span></p>
        <p><span>Ville :</span><span id=""> Sfax<span/></p>
    </div>
    <div class="col-xs-12 col-sm-6 col-md-6">
        <p><span>Tél. :</span> 74 400 202</p>
        <p><span>E-mail :</span><span id="email"> info@ggg.com.tn</span></p>
        <p><span>Nom du contact :</span><span id="nomContact"> nom</span></p>
        <p><span>Tél. Mobile :</span><span id="telephone"> 23 447454</span></p>
        <p><input type="hidden" id="id" value="2"/> </p>
    </div>
    <div class="clear"></div>
</div><!--content-action-->
{% endblock %}
{% block javascripts %}
<script>
        function functionClick(element){
        var id = $("#id").val();
            var route = '{{ path('client_edit', { 'id': "PLACEHOLDER" }) }}';
            route = route.replace("PLACEHOLDER", id);
             $.ajax({


                    //On lui indique le type d'envoie des informations

                    type: 'POST',

                    //On lui indique le chemin de la fonction

                    url:  route,



                    //On lui donne la valeur du choix qu'on a fait, et id est la variable qui va contenir notre valeur, nous la retrouvons dans notre controller




                    //Enfin nous lui disons de remplir notre formulaire avec le resultat  

                    success: function(response)

                    {

                        element.innerHTML= {{ the_first_fiels_of_the_form }};
                    }

                }

            );

        }

    </script>
 {% endblock %}

我希望在点击的元素中有the_first_fiels_of_the_form

我愿意:the_first_fiels_of_the_form ={{form_widget(editForm.raisonSociale)}} 但没有结果。

【问题讨论】:

  • 好的,让我们详细介绍一下:您能否提供进行 ajax 调用的模板(重要的部分,而不是全部)和模板ApplicationClientBundle:Client:index.html.twig
  • 渲染模板是否真的返回了一些东西? $answer 设置了吗?
  • json 响应为空:{"editForm":{"headers":{}}}

标签: javascript ajax symfony render


【解决方案1】:

我这样解决了我的问题:

在控制器中,我这样做:

public function editAction($id)
{
    if ($this->container->get('request')->isXmlHttpRequest()) {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('ApplicationClientBundle:Client')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Client entity.');
        }

        $editForm = $this->createEditForm($entity);

         return $this->container->get('templating')->renderResponse('ApplicationClientBundle:Client:cordonner.html.twig', array(
        'editForm' => $editForm->createView()
        ));
}

在模板"index.html.twig",我这样做:

{% block body -%}


...
 {% for entity in entities %}
    <tr>
        <td>{{ entity.raisonSociale}} </td>
        <td>{{ entity.login }}</td>
        <td>{{ entity.password }}</td>
        <td>{{ entity.soldeSMS }}</td>
        <td>

        <a class="modifier-client handler" data-id="{{ entity.id }}"><span class="glyphicon glyphicon1">Update</span></a>
        <a href="#historique" class="modifier-client"><span class="glyphicon glyphicon2">Voir Historique</span></a>
        <a href="#ajout" class="modifier-client"><span class="glyphicon glyphicon3">Ajout transaction</span></a>
        <input type="hidden" name="id_client" id="id_client" value=""/>
    </td>
</tr>

{% endfor %}

<div id="cordonner">
    {% include 'ApplicationClientBundle:Client:cordonner.html.twig' %}
</div>

...
{% endblock %}

{% block javascripts %}
$('.handler').click(function() {
            var id = $(this).data('id');
            var route = '{{ path('client_edit', { 'id': "PLACEHOLDER" }) }}';
            route = route.replace("PLACEHOLDER", id);
            $.ajax({


            //On lui indique le type d'envoie des informations

            type: 'POST',

            //On lui indique le chemin de la fonction

            url:  route,  //<==> editAction($id_customer_selected)



            //On lui donne la valeur du choix qu'on a fait, et id est la variable qui va contenir notre valeur, nous la retrouvons dans notre controller




            //Enfin nous lui disons de remplir notre formulaire avec le resultat  

            success: function(response)

            {

                $('#cordonner').html(response);
                $(".client").hide();
                $(".fich-client").show();
                document.location="#cordonner";


            }

        }

    )});
{% endblock %}

"cordonner.html.twig",我愿意:

{% if editForm is defined %}
    {{ form(editForm)}}
{% end if%}

【讨论】:

    【解决方案2】:

    尝试使用:

    use Symfony\Component\HttpFoundation\JsonResponse;
    

    及以后:

    $response = new JsonResponse();
    $response->setData(array('editForm'=> $answer));
    return $response;
    

    【讨论】:

      【解决方案3】:

      如果你只有一个渲染的模板,为什么要首先返回 json?

      public function editAction($id)
          {
              if ($this->container->get('request')->isXmlHttpRequest()) {
                  $em = $this->getDoctrine()->getManager();
      
                  $entity = $em->getRepository('ApplicationClientBundle:Client')->find($id);
      
                  if (!$entity) {
                      throw $this->createNotFoundException('Unable to find Client entity.');
                  }
      
                  $editForm = $this->createEditForm($entity);
      
      
                  return $this->render('ApplicationClientBundle:Client:index.html.twig', array(
                      'editForm' => $editForm->createView(),
                  ));;
              }
      
      
      
          }
      

      这将做同样的事情。它将返回一个 html 响应,您可以轻松地将其附加到视图中的 javascript 中。

      【讨论】:

      • 我不明白这个问题。 $this->render 的第二个参数是您提供给模板的数据数组。
      猜你喜欢
      • 2014-09-12
      • 1970-01-01
      • 2023-03-07
      • 2015-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-12
      相关资源
      最近更新 更多