Drupal 8 Redirect form on form submit

Problem:

I need to redirect a form to a specific URL on submit

Solution

  1. Add a custom submit on hook_form_alter();
    • Use either of the lines below

      $form['#submit'][] = 'mycustom_submit_function';
      // OR
      $form['actions']['submit']['#submit'][] = 'mycustom_submit_function';
  2. Then on the submit function use the below code
function mycustom_submit_function(array $form, FormStateInterface $form_state) {
$url = Url::fromRoute('<front>', [], ['absolute' => TRUE]));
$form_state->setRedirectUrl($url);

}

Sample for a complex url would be like

 

$url = Url::fromRoute('commerce_checkout.form', ['commerce_order' => $order_d,'step' => 'order_information'], ['absolute' => TRUE]);