I'm working on a Symfony 3.3 form, my problem is that by default, the form will submit a POST request back to the same controller that renders it (see: https://symfony.com/doc/3.3/forms.html). It's a problem for me because of how I built my controler function :
/**
* @Route("/login", name="project_login")
*
* @return Response
*/
public function loginAction(Request $request) {
// Get Keypad
$apiInstance = new AuthenticationApi();
$response = json_decode($apiInstance->middleKeypadGet());
if ($response->status == 200) {
// Create form base class instance
$loginForm = new LoginForm();
$loginForm->setKeypadId($response->id);
$loginForm->setKeypadLayout($response->keysLayout);
// Create form.
$form = $this->createForm(LoginType::class, $loginForm, array(
'keypadLayout' => $loginForm->getKeypadLayout(),
'keypadId' => $loginForm->getKeypadId(),
));
}
else {
//TODO Error Handling
return $this->render('Project:Login:login.html.twig');
}
// Handle request.
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
/** @var LoginForm $Login */
$response = $apiInstance->middleAuthenticationPost($loginForm->getUserId(), $loginForm->getKeypadId(), $loginForm->getUserPwd());
return $this->redirectToRoute('project_home');
}
return $this->render('Project:Login:login.html.twig', [
'form' => $form->createView(),
'path' => 'login'
]);
}
So when user try to GET my /login route everything goes fine, I'm getting keypad data from a GET call on another API endpoint and setting the value in my data-class (LoginForm) instance, then I create a form of type LoginType and I set the keypad infos from my data-class inside the form and then I render it. The problem occur when I'm submitting the form, my loginAction(Request $request) controller function is called again but this time with the POST request from submitting and here is the problem it redo my first part getting the keypad again (another keypad than the first one which is causing trouble and invalidate the authentication call later on) and then this time it goes in the if ($form->isSubmited() && $form->isValid()) part doing my authentication call but with wrong keypad data because the keypad call has been made two times.
I think I designed my controller badly, maybe I shouldn't do the keypad call here ? Maybe I should do it in my LoginForm class or LoginType class ? maybe I should make condition on GET/POST and do keypad call only if it's a GET ? Maybe I should POST my form data to another controller ? or use manual submit ? or create a service ? I'm a little lost after reading symfony doc and different web post I don't realy know what's the way to go and best practice.
You only want to execute that part of the code if it's not a submit. So you need to wrap a condition around it: