1

The project it's in Drupal 8.2

Hello, when a user fill the profile and Save ( /user/id/edit) the page it's reloaded with the new data in the same url, but I want to redirect the user to /user/id

This code should work:

function custom_user_form_user_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  $form_state->setRedirect('user.page');
}

But it doesn't work, any idea what's going on?

Thanks

  • Is this code called ? How is your module named ? – rémy Jan 30 '18 at 2:25
2

You can not set a redirect directly in the form alter. Submit callbacks are responsible for setting a redirect. You need to add a submit callback on the button after the default one and then set the redirect there.

3

You need to add a new submit handler to the form:

function custom_user_form_user_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['#submit'][] = 'custom_user_submit_handler';
}

Inside the new submit handler set the redirect:

function custom_user_submit_handler(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form_state->setRedirect('user.page');
}
  • Hello Colin, thank for the example, at the end you say the same that Berdir, but he answered first, it's why I give him the ok status. – Oskar Calvo Jan 30 '18 at 20:45
0

In this case this is the correct code to make it works.

/**
 * Implement hook_form_id_alter()
 */
function custom_user_form_user_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['actions']['submit']['#submit'][]= 'custom_user_custom_submit_handler';
}

/**
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @param $form_id
 */
function custom_user_custom_submit_handler(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  $form_state->setRedirect('user.page');
}

Thanks to Berdir and Colin by their helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.