Symfony3 - 使用生成的表单使用ajax添加数据

时间:2016-10-14 11:59:35

标签: javascript jquery ajax symfony symfony-forms

所以我所做的就是在类实体参数上生成formtype base,然后返回json中的视图,并且使用ajax工作正常 这是控制器中的目标路径:

/**
     * @Route("/{action}/{class}/{pk}",
     * name="manage",
     * defaults={"pk": "-1"},
     * options={"expose": "true"},
     *     requirements={
     *         "action": "^(ajouter|modifier|supprimer)$"}
     * )
     */
    public function manageAction($action, $class, $pk, Request $request) {

        if ($request->isXmlHttpRequest()) {
            $entityPath = 'PlatformBundle\Entity\\' . $class;
            $formTypePath = 'PlatformBundle\Form\\' . $class . 'Type';
            $twigformview = strtolower($class) . "form.html.twig";


            if ($action == 'ajouter') {
                $obj = new $entityPath;
            } else {
                $obj = $this->getDoctrine()->getRepository('PlatformBundle:' . $class)->find($pk);
            }

            $form = $this->createForm($formTypePath, $obj);

            $form->handleRequest($request);
            if ($form->isSubmitted() && $form->isValid()) {
                $obj = $form->getData();
                $em = $this->getDoctrine()->getManager();
                try {
                    if ($obj) {
                        if ($action == 'supprimer') {
                            $em->remove($obj);
                            $em->flush();
                        } else {
                            $em->persist($obj);
                            $em->flush();
                            return new JsonResponse(array('respond' => 'true'));
                        }
                    }
                } catch (Exception $ex) {
                    return new JsonResponse(array('respond' => 'false'));
                }
            }

            $myHtmlText = $this->renderView('PlatformBundle:Gestion:' . $twigformview, array(
                'form' => $form->createView(),
                'table' => $class,
                'action' => $action
            ));

            $response = new JsonResponse();
            $response->setData(array('entity' => $class, 'action' => $action, 'htmltext' => $myHtmlText));
            return $response;
        }
    }

点击添加新按钮后弹出一个模态弹出并用html返回填充:

$('#addButton').click(function () {

        $.ajax({
            type: 'post',
            url: Routing.generate('manage', {action: 'ajouter', class: 'Fournisseur'}),
            beforeSend: function () {
                $('#modalTitle').html("Chargement...");
                $('#modalBody').html('<div><p align="center"><img src="../../assets/img/loading-circle.gif" with="80" height="80"></p>\n\
                                            <p align="center">Création du formulaire en cours...</p></div>');
                $('#gesModal').modal('show');
            },
            success: function (data) {

                $('#modalTitle').html(data.action + " " + data.entity);
                $('#modalBody').html(data.htmltext);
            },
        });
    });

直到这里一切都很好但是当我点击按钮时添加模态没有任何反应:

/* ---------- Ajout  ---------- */
    $('#ajouterFournisseur').click(function () {
        $.ajax({
            type: 'post',
            url: Routing.generate('manage',
                                  {action: 'ajouter', class: 'Fournisseur', fournisseur: {
                                      libellef: $('#fournisseur_libellef').val(),
                                      emailf: $('#fournisseur_emailf').val(), 
                                      telf: $('#fournisseur_telf').val(), 
                                      adressef: $('#fournisseur_adressef').val(), 
                                      codeEntreprise: $('#fournisseur_codeEntreprise').val(),
                                      _token: $('#fournisseur__token').val() }
                                  }),
            async: true,
            dataType: "json",
            success: function (data) {
                console.log(data);
            },
        });
    });

以及更多详细信息,这是视图代码:

{{ form_start(form, { 'attr': {'class': 'form-horizontal'} }) }}



                {{ form_widget(form.libellef, { 'attr': {'class': 'form-control',
                                                  'autofocus': ''} }) }}

                    {{ form_widget(form.emailf, { 'attr': {'class': 'form-control',
                                                  'placeholder': 'nom@domaine.ex',
                                                  'type-data': 'email'} }) }}

                    {{ form_widget(form.telf, { 'attr': {'class': 'form-control tel',
                                                  'type-data': 'tel'} }) }}

                    {{ form_widget(form.adressef, { 'attr': {'class': 'form-control'} }) }}

                    {{ form_widget(form.codeEntreprise, { 'attr': {'class': 'form-control',
                                                  'type-data': 'codeEntreprise'} }) }}

        <button type="button" id="{{ action ~ table }}" class="btn btn-primary">{{ action }}</button>
        {% if action != 'supprimer' %}
            <button type="reset" class="btn btn-inverse">vider</button>
        {% endif %}

    {{ form_end(form) }}

我已经停留在这2天了,现在搜索并尝试了很多,但我总是得到同样的问题谢谢!

1 个答案:

答案 0 :(得分:0)

我发现javascript端的解决方案已将ajax发送请求更改为提交表单:

$('form[name="fournisseur"]').on('submit', function (e) {
        e.preventDefault();
        $.ajax({
            url: Routing.generate('manage', {action: 'ajouter', class: 'Fournisseur'}),
            type: "POST",
            data: $(this).serialize(),
            beforeSend: function () {
                $('#alertMessage').html('<img src="../../assets/img/loading-circle.gif" with="30" height="30"> En cours ...');
            },
            success: function (data) {
                console.log(data);
                if(data.respond == 'true'){
                 $('#alertMessage').addClass("alert alert-success");
                $('#alertMessage').html('<button type="button" class="close" data-dismiss="alert">×</button>\n\
                <strong>Ajout</strong> Opération effectuer avec succée.');
                }
            },
            error: function (jXHR, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
    });
相关问题