Drupal Problems and Solutions

DrupalABC aims to provide solutions to programming problems faced by Drupal developers. Start learning by reading some of the latest problems below. You can also learn website building in Drupal 9 by reading the website building guide.

How to attach library using hook_preprocess_page?

Hook preprocess can be used to attach libraries on any page in Drupal 8 based on any condition. Developers can also add drupalSettings variable. Here is the code snippet:

 * Hook_preprocess_page().
function example_preprocess_page(&$variables) {

  $variables['#attached']['library'][] = 'example_module/example_library';

  $variables['#attached']['drupalSettings']['siteBaseUrl'] = 'example.com';



How to set entity form and entity view display settings programatically

Entity form display and Entity view display control which fields are shown in entity creation form and entity display page. Drupal provides complete control of fields and widgets through the user interface. We can also set these settings programmatically by loading correct configuration. 

    $settings = \Drupal::entityTypeManager()

So when we run this snippet body field is removed from form display while creating a product of product type default. Feel free to experiment by setting other available configurations in configuration file of type entity view display and entity form display.  

How to set address field programatically in Drupal 8

Address field consists of various sub values which can be configured accordingly. To set an address field programmatically use the following snippet.

        $address = [
          'country_code' => 'IN',
          'address_line1' => 'Test Address Line 1',
          'address_line2' => 'Test Address Line 2',
          'locality' => 'City',
          'administrative_area' => 'New Delhi',
          'postal_code' => '110001',

$entity-set('field_address', $address);


How to send POST request with basic authentication and exception handling

Most of the times the POST request endpoints are protected by basic authentication. Accessing them might give errors such as access denied or 500 internal server error. Here is post request snippet in Guzzle to handle requests in such cases.

try {
      $client = \Drupal::httpClient();
      $request = $client->post('/example-post-url/', [
        'auth' => ['username', 'password'],
        'json' => [
          'data' => $data,
      $response = json_decode($request->getBody(), TRUE);
    catch (RequestException $error) {
     $error_message =  $error->getMessage();