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

}

How to load a form in a block in Drupal 8

You can use the following block code to load a form in a block in Drupal 8.

<?php

namespace Drupal\example_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'ExmpleFormBlock' block.
 *
 * @Block(
 *  id = "ExampleFormBlock",
 *  admin_label = @Translation("Example Form Block"),
 * )
 */
class ExampleFormBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    return \Drupal::formBuilder()->getForm('Drupal\example_module\Form\ExampleForm');
  }

}
 

Example Form is the class of form which has to be displayed in the block. You can also use core and contributed provided forms.