2

I need to POST the data in a form to an external URL.

In Drupal 7, you would use

$form['#action'] = url('http://example.com', array('external' => true));

Or maybe this was for GET. Anyway... in Drupal 8, this does not work. I have tried editing the submitForm method:

public function submitForm(array &$form, FormStateInterface $form_state) {
    $response = new TrustedRedirectResponse('http://example.com');
    $response->send();
}

This works, however I have not found a way to submit the values of the form along with the request. I looked at the httpClient class, but it seems that is for sending/requesting data only and does not redirect the user.

Hope someone can help me out. If it comes down to it I am fine with using GET instead.

1
  • As side note, in Drupal 7 url('http://example.com', array('external' => true)); is perfectly useless; just use 'http://example.com'. url() just returns a string, not an object.
    – apaderno
    Jun 17, 2016 at 6:31

3 Answers 3

3

$form['#action'] works the same, Drupal 7 or Drupal 8. It needs a string, which is what url() returns in Drupal 7. The reason why url() is normally used is because the code has a relative path for a routing item, such as in url('comment/reply/'. $edit['nid']).

In Drupal 8, for example, the Comment module uses the following code.

$form['#action'] = $this->url('comment.reply', array('entity_type' => $entity->getEntityTypeId(), 'entity' => $entity->id(), 'field_name' => $field_name));

UrlGeneratorTrait::url(), the method called in that code, still returns a string, not an object. Also in this case, UrlGeneratorTrait::url() is used because the code has a route name (comment.reply) and it wants to get the URL for that route.

The following code works for Drupal 7 and Drupal 8.

$form['#action'] = 'http://example.com';
1

OK I figured it out. It turns out that the Drupal 7 method works, however there is no longer a need to submit a URL object, just a string containing the URL. So

$form['#action'] = url('http://example.com', array('external' => true));

becomes simply

$form['#action'] = 'http://example.com';

2
  • but if you do this, you skip the validation
    – Diana
    Apr 26, 2017 at 16:00
  • 1
    FYI, the Webform module now supports POST to external URLs.
    – Kevin
    Aug 6, 2017 at 15:15
0

your sample code would work just fine for simple redirection.

However for posting data to external URL, this should work i believe,

$response = \Drupal::httpClient()->post($host, [
        'form_params' => $fields,
        'headers' => [
          'Content-type' => 'application/x-www-form-urlencoded',
        ],
    ]);

Answered Similar Question in https://drupal.stackexchange.com/a/288929/18756

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.