Skip to main content

Drupal 8: Form redirection on submit. How to redirect to a views page with query parameters

This is a basic example on how to redirect a form after submission. In your web/modules/custom/my_custom_module/src/Form/customModuleForm.php class add this in your submitForm method. 

//Do not forget to use the Drupal Core URL namespace Class
use Drupal\Core\Url;
class customModuleForm extends FormBase {
....
  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state_values = $form_state->getValues();
    if (isset($form_state_values['alpha_param'])) {
      $redirect_params['alpha_param['.$form_state_values['alpha_param'].']'] = $form_state_values['alpha_param'];
    }

    if (isset($form_state_values['beta_param'])) {
      $redirect_params['beta_param['.$form_state_values['beta_param'].']'] = $form_state_values['beta_param'];
    }

     $url = Url::fromRoute('view.view_machine_name.page_1', $redirect_params);
    $form_state->setRedirectUrl($url);
  }
}

Notice that i do a redirect to a custom views page. In order to use the route name of a view page the pattern is

view.{view_machine_name}.{view_display_page_id}

If you want to redirect to another core route here are some examples.

Redirect to the user page ( Redirection on form submit)
$form_state->setRedirect('user.page');

Redirect to a custom page
$form_state->setRedirect('your.custom_module.route.name');

 

 

URL