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.

1
  • 2
    $form_state->setRedirectUrl
    – user21641
    Commented Jun 12, 2017 at 11:46

1 Answer 1

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').

5
  • 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); ?
    – Cool
    Commented Jun 12, 2017 at 13:01
  • 1
    $url = \Drupal::service('path.alias_manager')->getAliasByPath($system_path, $langcode), where $system_path is "/node/$nid"
    – Clive
    Commented Jun 12, 2017 at 13:07
  • @Clive, I have updated my code in above question. Still it is not working. Throwing error like route not exists.
    – Cool
    Commented Jun 12, 2017 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
    Commented Jun 12, 2017 at 13:47
  • @ARUN Use $form_state->setRedirectUrl(Url::fromUri('//my_node_alias')).
    – avpaderno
    Commented Jun 12, 2017 at 14:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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