I am trying to add an additional submit handler to the user login form, to simply redirect users to the page they were on before landing on the login page (/user/login).
I have the following code attempting to store the current path/destination in the $form_state storage which is working as I expected when the original form_alter is run on render as it alters the redirect property of form_state to the previous page.
However, when the form is submitted, the form_alter is fired again, but this time the form_state storage is empty, thus the current_path/destination is now set to /user/login which is not where the user should be redirected to.
Here is the code I have at the moment, any help would be appreciated as to why the form_alter is run again on form submit:
function MODULE_form_user_login_form_alter(&$form, FormStateInterface $form_state, $form_id) {
$form['#submit'][] = '_module_custom_user_login_form_submit';
if (is_null($form_state->get('redirect_dest'))) {
$destination = $_SERVER['HTTP_REFERER'];
$form_state->set('redirect_dest', $destination);
}
}
function _module_custom_user_login_form_submit($form, FormStateInterface &$form_state) {
$destination = $form_state->get('redirect_dest');
$form_state->setRedirect($destination);
}