Drupal Problems and Solutions

DrupalABC aims to provide solution to programming problems faced by Drupal developers.Start learning by reading some of the latest problems below-

How to redirect to a page after form submit in Drupal 8

You can redirect the user to any page after form submission in the following way.

//Don't forget to include this in beginning. This will only work in submitForm function.
use Drupal\Core\Url;
//Constructing a URL.Will redirect to example-page with query paramter q = 5.
$response = Url::fromUserInput('/example-page?q=5');


How to send POST request in Drupal 8

In Drupal 8 POST request can be sent using Guzzle http library in the following way.


//Creating a httpClient Object.
$client = \Drupal::httpClient();
//Some Data
$json_data = ['a'=>5,'b'=>6,'c'=>7];
//Sending POST Request with $json_data to example.com
$request = $client->post('http://example.com', [ 'json' => [ $json_data, ]
//Getting Response after JSON Decode.
$response = json_decode($request->getBody());