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 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()
      ->getStorage('entity_form_display')
      ->load('commerce_product.default.default')
      ->removeComponent('body')->save();

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);

$entity->save();

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();

}