2

How do I redirect users after they submit a form? I tried the following code, but it doesn't work. It says the route doesn't exist.

public  function submitForm(array &$form, FormStateInterface $form_state){
   $url = Url::fromRoute('/mon-profil/obtenir_document'); // == /node/1
   $form_state->setRedirectUrl($url);
}
1
  • fromRoute() takes the route name as the argument, not a literal path.
    – Kevin
    Oct 22, 2017 at 22:18

2 Answers 2

0

You are using the wrong method: Url::fromRoute() is expecting the route name, as Kevin said.
If you really need to use a path alias, which would allow you to change the redirect without editing your code (which would keep referring the same path alias), you need to use Url::fromUserInput() that accepts a path starting with /, which also include a path alias, if you remember to add a slash at the beginning.

As side note, if you want to redirect users using a route, you don't first need to get a Url object: Use FormState::setRedirect(), which accepts a route name.
Using a route (for example the one used by Kevin's example), your code would become the following one.

public  function submitForm(array &$form, FormStateInterface $form_state){
   $form_state->setRedirect('entity.node.canonical', ['node' => 1]);
}

In my example, I hard-coded the node ID, but real code would probably get it in a different way. For example, the module could create a node, store its node ID using the state API, and use the state API to retrieve it.

0
2

You're getting that error because fromRoute() takes the route name as the argument, not a literal path.

Assuming you know the node id you want to redirect to:

$url = Url::fromRoute('entity.node.canonical', array('node' => $node_id));

You don't ever want to redirect to internal paths like that (in your question) because they are subject to change.

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.