How to redirect to external URL upon form submission I've extended a FormBase and I've defined the submitForm method. In this method I want to redirect to an external URL (https://example.com/my/path?amount=33&amp;gift=0&amp;product_id=1)

$myurl = "https://example.com/my/path?amount=33&amp;gift=0&amp;product_id=1";
$redirect = Url::fromUri($myurl);
$form_state-&gt;setRedirectUrl($redirect);


And I get the error:

Redirects to external URLs are not allowed by default, use \Drupal\Core\Routing\TrustedRedirectResponse for it.


Ok, no problem, let's create one:

$myurl = "https://example.com/my/path?amount=33&amp;gift=0&amp;product_id=1";
$redirect = new TrustedRedirectResponse($myurl);
$form_state-&gt;setRedirectUrl($redirect);


Here's the error:

Argument 1 passed to Drupal\Core\Form\FormState::setRedirectUrl() must be an instance of Drupal\Core\Url


So it appears we've gone full circle. Is there a way that maybe I can convert the TrustedRedirectResponse to a Url object?
You'll want to use $form_state-&gt;setResponse() instead to utilize the TrustedRedirectResponse you're creating.

Something like this should work:

public function submitForm(array &amp;$form, FormStateInterface $form_state) {
  // Do form stuff...

  $myurl = "https://example.com/my/path?amount=33&amp;gift=0&amp;product_id=1";
  $response = new TrustedRedirectResponse(Url::fromUri($myurl)-&gt;toString());
  $form_state-&gt;setResponse($response);
}


This response may be cached depending on your page cache settings. If you need to change this behavior, you can modify the caching metadata. This should disable this type of caching completely for the response (not tested):

public function submitForm(array &amp;$form, FormStateInterface $form_state) {
  // Do form stuff...

  $myurl = "https://example.com/my/path?amount=33&amp;gift=0&amp;product_id=1";
  $response = new TrustedRedirectResponse(Url::fromUri($myurl)-&gt;toString());

  $metadata = $response-&gt;getCacheableMetadata();
  $metadata-&gt;setCacheMaxAge(0);

  $form_state-&gt;setResponse($response);
}