Search code examples
ajaxsymfonypostentitymanager

How can I post my Object via Ajax and store int into the database via Entity Manager?


$('#form_save').on( 'click', function (e) {
      e.preventDefault();
      var form = $(this).closest('form');
      var formData = form.serializeArray();

      alert(formData.toSource());
      $.ajax({
        method:'POST',
        url:'{{ path('edit_form', { 'slug': page.slug }) }}',
        data: formData,
        success: function(data){

          alert("success");
        }
      });
    });

var formData is giving me the following alert output:

[{name:"form[username]", value:"1"}, {name:"form[email]", value:"1@12.sw"}, {name:"form[is_active]", value:"1"}, {name:"form[plainPassword][first]", value:""}, {name:"form[plainPassword][second]", value:""}, {name:"form[_token]", value:"MdSCmPgzZC3pZaW2wK2Rk"}]

How can I use this now into my Controller to store it into the database:

public function form($slug, Request $request){

    $id = $request->request->get('id');

    $item = new User();
    $item= $this->getDoctrine()->getRepository(User::class)->find($id);

    if($request->request->get('data')){

         $data = $request->request->get('data');
         $entityManager = $this->getDoctrine()->getManager();
         $entityManager->flush();
       }
    }

I get the error message:

The identifier id is missing for a query of App\Entity\User

Solution

  • Since you are using jQuery and you are just trying to submit an edit-user form I would initially suggest to use malsup's ajaxForm plugin. Of course you can implement the same functionality with FormData and ajax request.

    In case you use ajaxForm plugin, you just have to set properly your form's action (the route should be something like this: /edit-user/1 where 1 is user's id) and the javascript code will just look like this:

    $('form#your-form').ajaxForm({
        success: function(response){ alert("success"); }
    });
    

    The Symfony Controller will look like this:

    public function form(User $user, Request $request){
        $form = $this->createForm(UserType::class, $user);
    
        $form->handleRequest($request);
    
        if ($form->isSubmitted() && $form->isValid()) {
    
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->flush();
        }
    
        return $this->json('success');
    }