0

How can I redirect users to a node in a form submission handler similarly to the following code?

In my form alter I have added an additional submit button:

$form['actions']['save_and_exit'] = array(
    '#type' => 'submit',
    '#value' => t('Save & Exit'),
    '#submit' => array('custom_submit'),
  );

function custom_submit(&$form, \Drupal\Core\Form\FormStateInterface 
  $form_state) {
    $syst‌​em_path = '/node/2';
    $url = \Drupal::service('path.alias_manager')->getAliasByPath($syst‌​em_path);
    $form_state->setRedirect($url);
}

Then I'm getting following error:

Symfony\Component\Routing\Exception\RouteNotFoundException: Route "/mypage" does not exist. in Drupal\Core\Routing\RouteProvider->getRouteByName() (line 190 of C:\wamp\www\www_assure_local_com\core\lib\Drupal\Core\Routing\RouteProvider.php).

where /mypage is the url alias of my /node/2.

  • 2
    $form_state->setRedirectUrl – user21641 Jun 12 '17 at 11:46
2

A form submission handler never returns a RedirectResponse object to redirect users. (It actually doesn't return any value.)

A form submission handler calls FormState::setRedirect(), or FormState::setRedirectUrl() which accepts a Url object, for example the value returned from Url::fromUri('//my_node_url_alias').

| improve this answer | |
  • Sorry.. I'm not clear on that. how could I put it submit function? like this $url = Url::fromUri('//my_node_url_alias'); FormState::setRedirectUrl($url); ? – ARUN Jun 12 '17 at 13:01
  • 1
    $url = \Drupal::service('path.alias_manager')->getAliasByPath($system_path, $langcode), where $system_path is "/node/$nid" – Clive Jun 12 '17 at 13:07
  • @Clive, I have updated my code in above question. Still it is not working. Throwing error like route not exists. – ARUN Jun 12 '17 at 13:26
  • 1
    Read api.drupal.org/api/drupal/… and api.drupal.org/api/drupal/…, you need to use one of those with the correct parameters – Clive Jun 12 '17 at 13:47
  • @ARUN Use $form_state->setRedirectUrl(Url::fromUri('//my_node_alias')). – kiamlaluno Jun 12 '17 at 14:57

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.