Starting my journey with symfony and development, I am faced with the task of editing an object using a form embedded in a popup. Here's how I handle it:
First, I use JavaScript along with AJAX to send the data "id" to locate the object based on its id. Subsequently, I include the form data for modifying this object using the following JS code:
$('.btn-edit').click( function() {
$(this).val();
console.log("edit clicked " + $(this).val());
let id = $(this).val();
let DATA = {'id':id};
let url = '/edit'
$.ajax({ // Sending a request with player ID as data.
type: "POST",
url: url,
data: JSON.stringify(DATA),
contentType: "application/json; charset=utf-8",
dataType: 'html',
cache: false,
success: function (data3) { // Editing action result: including form in a popup
$('#modal_detail').html(data3); // fetching the form
$('#modal-title').html("Edit Player"); // Displaying Popup Title
$('#dataModal').modal("show"); // Showing the popup
// Sending the form data
$('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);
}
});
});
}
});
});
Check out my controller code snippet 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 suspect an issue in processing user-filled form data within my controller logic. While trying to decode the form data with JSON to extract the id, it seems redundant since I have already sent the id initially...
This dilemma has left me stuck, seeking assistance to untangle this situation. Your guidance would be greatly appreciated!