The other day I was tasked with redirecting the Drupal login form to the user account page. On any other form this would work by adding the #redirect tag to the form in a form alter function like this:
// Incorrect method, this doesn't work for the user login forms.
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
switch($form_id) {
case 'user_login_block':
case 'user_login':
$form['#redirect'] = 'user';
break;
}
}
However, the user login form uses the 'destination' URL parameter which overrides the #redirect in the form. In order to force the user login form and the user login block to redirect I needed to use the destination URL parameter like this:
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
switch($form_id) {
case 'user_login_block':
case 'user_login':
// Explode the form action and get the query string.
$url = explode('?', $form['#action']);
// Replace the query string with the destination I want, in this case the 'user' page.
$form['#action'] = $url[0] . '?destination=user';
break;
}
}