Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
Problem/Motivation
Form state has some methods for making redirects but it doesn't allow for redirecting to external URLs because it doesn't create "trusted" redirects. This is generally fine, a module may want to have more control and redirect to a trusted URL.
Timplunkett gave me the following workaround which works for the moment but seems fragile.
$form_state->setFormState(['redirect' => new TrustedRedirectResponse("http://example.com")]);
Proposed resolution
Allow settings a redirect directly on the form state. something like
$form_state->setRedirectResponse(new TrustedRedirectResponse());
Remaining tasks
User interface changes
No
API changes
API addition.
Data model changes
No
Comments
Comment #2
neclimdulderp. functional workaround.
Comment #3
dawehnerCan't you use the following code:
Comment #4
tim.plunkettOh you totally can. From FormSubmitter::doSubmitForm():
And we have test coverage for this in \Drupal\Tests\Core\Form\FormSubmitterTest::testHandleFormSubmissionWithResponses().
Comment #5
neclimdul*facepalm*
Comment #6
yched CreditAttribution: yched commentedStumbled on this as well.
The confusing thing is that :
- FormState::$redirect / FormStateInterface::getRedirect() are documented as being "a URL or a RedirectResponse",
- FormSubmitter::redirectForm() does contain explicit code to handle the case where $form_state->getRedirect() is a RedirectResponse,
while :
- there is in fact no API way to actually set it to be a RedirectResponse :-)
- and the only way to obtain the desired effect is to use a different API ($form_state->setResponse())