0

So what i did is generate formtype base on class entity param given after that i return the view in json and that's working fine with ajax here is target route in controller :

/**
     * @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;
        }
    }

after clicking add new button a modal popup and fill it with html returned :

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

until here everything is fine but when i click on button add in the modal nothing happens:

/* ---------- 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);
            },
        });
    });

and for more details this is the view code :

{{ 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) }}

I'm stuck at this 2 days now search and try a lot but always i got same problem thank you !

Souf
  • 611
  • 2
  • 14
  • 36
  • Is anything actually being sent to the server when you press the add button? If you don't know then press F12 in your browser and click the network tab. That shows you network traffic. – Cerad Oct 14 '16 at 12:32
  • just did it sends all data but i kind know what the probleme is @Cerad how do i convert the 'fournisseur' js array into object of entity without using setters – Souf Oct 14 '16 at 12:45
  • Your code is a bit of a puzzle to me but assuming your controller action is being called then http://stackoverflow.com/questions/9522029/posting-json-objects-to-symfony-2 shows how to get the json payload. After that you could either use a seralizer to go to an entity or possibly use $form->submit() https://symfony.com/doc/current/form/direct_submit.html#calling-form-submit-manually to let the form do it. – Cerad Oct 14 '16 at 12:58

1 Answers1

0

I've found the solution in javascript side changed that ajax send request to a submit form :

$('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);
            }
        });
    });
Souf
  • 611
  • 2
  • 14
  • 36