3

How can I redirect users in a custom module after saving a user account with $user->save()? It always goes to the user profile after saving and I want to redirect to a custom page.

function user_update_redirect(&$form, $form_state) {
  $value1 = $form_state->getValue('panel');
  $value2 = $form_state->getValue('type_of_user');
  $storage = \Drupal::service('entity_type.manager')->getStorage('taxonomy_term');
  $user = \Drupal::currentUser();
  $user = user_load($user->id());
  $user->set('field_panel', $value1);
  $user->set('field_type_of_user', $value2);
  kint($user);
  $user->save();
}
3
$form_state->setRedirectUrl(Url::fromUserInput($redirect_path));
  • 1
    Welcome to Drupal Answer! Thank you for your answer. Please try to elaborate it a bit. Why this snippet, how to use it, in what function, what is $redirect_path? One-line answers don't provide that much of a value for future readers. Thanks! And keep up the good work. – leymannx Oct 5 '18 at 10:15
2

I suppose you want to remain on your site when redirecting. I don't recommend hardcoded URL's anywhere else but in route.yml files. Call the right service and don't forget to use dependency injection in your services and don't use a trait or directly call it from the container.

  private function redirect(string $route) {
    $path = $this->container->get('url_generator')->getPathFromRoute($route);
    return new RedirectResponse($path);
  }
  • The OP is showing the code of a form submission handler. It's not clear how a form submission could use the code shown here. – kiamlaluno Jan 25 '19 at 9:07
  • Well OP's code snippet does not tell much what the context is. So it's hard to tell how he should exactly use this. – ssibal Feb 4 '19 at 13:58
  • user_update_redirect(&$form, $form_state) could be either a form submission or a form validation handler. Given the OP is saving a user account inside it, it's probable it's a form submission handler. In any case, using $form_state it's possible to redirect the users without creating any redirect response. – kiamlaluno Feb 4 '19 at 14:15
1

After $user->save(); add

  $url = Url::fromRoute('route.name');
  $response = new RedirectResponse($url->toString());
  // $response = '/some/path';
  $response = new \Symfony\Component\HttpFoundation\RedirectResponse($response);
  $response->send();

  • 3
    You don't want to be sending your own response in the middle of form processing - unpredictable things can happen – Clive Oct 5 '18 at 13:12
0

In user_update_redirect(), which gets a FormState object, you can call one of the following methods.

FormState::setRedirect() is preferable when the redirecting URL is associated with a route, such as in the case of nodes, user accounts, or other entities. In the other cases, such as redirecting to external URLs, FormState::setRedirectUrl() is the method to use.

Returning a RedirectResponse object in a form submission handler doesn't have any effect. The method calling (FormSubmitter::executeSubmitHandlers) the form submission handlers discard the value returned from them.

  $handlers = $form_state->getSubmitHandlers();

  // Otherwise, check for a form-level handler.
  if (!$handlers && !empty($form['#submit'])) {
    $handlers = $form['#submit'];
  }
  foreach ($handlers as $callback) {

    // Check if a previous _submit handler has set a batch, but make sure we
    // do not react to a batch that is already being processed (for instance
    // if a batch operation performs a
    //  \Drupal\Core\Form\FormBuilderInterface::submitForm()).
    if (($batch =& $this->batchGet()) && !isset($batch['id'])) {

      // Some previous submit handler has set a batch. To ensure correct
      // execution order, store the call in a special 'control' batch set.
      // See _batch_next_set().
      $batch['sets'][] = [
        'form_submit' => $callback,
      ];
      $batch['has_form_submits'] = TRUE;
    }
    else {
      call_user_func_array($form_state->prepareCallback($callback), [
        &$form,
        &$form_state,
      ]);
    }
  }

Calling RedirectResponse::send() from a from submission handler would just interrupt what Drupal is doing when processing a form, including calling other form submission handlers and other hooks.

In the case there is the need to use FormState::setRedirectUrl(), the Url object should be built from Url::fromUserInput() only when the relative URI was given by user input (for example, when users fill a setting form for giving a redirect path). For an external URL well known from the module implementing the form submission handler, Url::fromUri() should be used.

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.