Edit an object with popup form and ajax request

Viewed 181

I'm developing with symfony (just starting out). I want to edit an object with a form that is included in my popup.

In my javascript, with ajax I send an "id" data to find the object with its id. Then, I also send the data that was put in the form in order to be able to modify this object (the js code below):

    $('.btn-edit').click( function() {

        $(this).val();
        console.log("click edit " + $(this).val());

        let id = $(this).val();
        let DATA = {'id':id};
        let url = '/edit'

        $.ajax({  // Envoie une requête avec en donnée l ID du player.
            type: "POST",
            url: url,
            data: JSON.stringify(DATA),
            contentType: "application/json; charset=utf-8",
            dataType: 'html',
            cache: false,
            success: function (data3) { // résultat de action edit : inclusion du formulaire dans un popup
                $('#modal_detail').html(data3); // récupère le formulaire
                $('#modal-title').html("Modifier player"); //Affiche Le titre de popup
                $('#dataModal').modal("show"); //Affichage du popup

                //envoie des données rentrées dans le formulaire
                $('form').submit(function(e) {
                    e.preventDefault();
                    let $formplayer = $(this);
                    let route = '/edit';
                    let datas = $formplayer.serialize();
                    $.post({
                        type: 'post',
                        url: route,
                        data: datas,
                        success: function(result) {
                            console.log(result);
                            $('.formMessage').addClass('success').html(result);
                            location.replace('/');
                        },
                        error: function(err){
                            $('.formMessage').addClass('success').html(err);
                        }
                    });


                });

            }
        });

    });

My controller code below:

/**
     * @Route ("/edit", name = "edit")
     *
     * @param $request
     *
     * @return RedirectResponse
     *
     * @throws JsonException
     */
    public function editPlayer(Request $request, PlayerRepository $playerRepository): Response
    {
        $em = $this->getDoctrine()->getManager();

        $post_data = json_decode($request->getContent(), true, 512, JSON_THROW_ON_ERROR);
        $id = $post_data['id'];

        $player = $this->getDoctrine()
                ->getRepository(Player::class)
                ->find($id);

        $form = $this->createForm(PlayerFormType::class, $player);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($player);
            $em->flush();

            return $this->redirectToRoute('player');
        }

        return $this->render('manager_temp/edit.html.twig', [
            'player' => $player,
            'form' => $form->createView(),
        ]);
    }

I think the data filled in by the user in the form is not processed well in my contoller. When the controller receives the form data it wants to decode with json to know the id. However I have already sent the id ...

I know my problem is a bit hazy :) But I need help I'm stuck ...

1 Answers

In fact, it was not difficult. You can send the id with the URL:

AJAX:

let DATA = {'id': id};
let url = '/ edit /' + id;

In controller:

* @Route ("/ edit / {id}", name = "edit")

So you can send the data form without JSON

Related