1

I have used the following code on submit of a form to first send the form contents via guzzle and then redirect the form. I get the error

Error: Call to undefined function TrustedRedirectResponse()

this is my code:

use Drupal\Core\Routing\TrustedRedirectResponse;

function mymodule_submit(&$form, FormStateInterface $form_state){
$url="xyz.com";
$post_data=array("color"=>"red");

$client = \Drupal::httpClient();
  $response = $client->request('POST', $url, [
    'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'],
     'verify'=>false,
    'form_params' => $post_data,

     ]);
    $status = $response->getStatusCode();

    $response = TrustedRedirectResponse(Url::fromUri($url));
    $form_state->setResponse($response);
}

I have two questions - how can I avoid the error , and is the order of getting the guzzle response and then getting the redirect response the correct order?

2 Answers 2

5

Your order seems correct, you need to instanciate a new TrustedRedirectResponse object like:

$response = new TrustedRedirectResponse($url_string);
-2

The client->request is then unnecessary

 function my_module_submit(&$form, FormStateInterface $form_state) {
      $block = Block::load('bid');
      $block_settings = $block->get('settings');
      $url = $block_settings['url'];
      $query=$form_state->getValue('search_query');
      if (!empty($query)) {
        $url .= $query;
      }
      $response = new TrustedRedirectResponse($url);
      $form_state->setResponse($response);
    }
1
  • This answer is just duplication and does not provide any useful information. $client->request() is just part of the surrounding example code, just like $block = Block::load('bid'); in your anwer is an example for block loading and unnecessary for a trusted response.
    – Hudri
    Commented Apr 4, 2023 at 14:32

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.