Last active
March 10, 2023 05:08
-
-
Save prashantdsala/47ee53f051d3c4b36619b526e4e2aa2e to your computer and use it in GitHub Desktop.
How to redirect from a Form using setRedirectUrl() method in Drupal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
In the submitForm() method of your form class, create a new instance of the RedirectResponse class, which is used to redirect to a new URL. | |
// Use the setRedirectUrl() method to set the URL to which you want to redirect. You can pass the URL as a string or as an instance of the Url class. | |
// Return the RedirectResponse object from the submitForm() method to trigger the redirect. | |
// Here's an example of how to use setRedirectUrl() in a form class: | |
use Drupal\Core\Form\FormStateInterface; | |
use Drupal\Core\Routing\RedirectDestinationInterface; | |
use Drupal\Core\Url; | |
use Drupal\Core\Form\FormBase; | |
use Symfony\Component\HttpFoundation\RedirectResponse; | |
class MyForm extends FormBase { | |
public function getFormId() { | |
return 'my_form'; | |
} | |
public function buildForm(array $form, FormStateInterface $form_state) { | |
// Build your form elements here. | |
return $form; | |
} | |
public function submitForm(array &$form, FormStateInterface $form_state) { | |
// Get the URL to which you want to redirect. | |
$url = Url::fromRoute('my_route'); | |
// Create a new RedirectResponse object. | |
$response = new RedirectResponse($url->toString()); | |
// Set the redirect destination. | |
$response->setRedirectDestination( | |
\Drupal::service('redirect.destination')->get() | |
); | |
// Set the redirect URL using setRedirectUrl(). | |
$response->setRedirectUrl($url); | |
// Return the RedirectResponse object. | |
return $response; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment