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 handle form submission using JS in Drupal 7

In Drupal 7 you use behaviors to handle the form submission. It can be achieved in following way.

  $form = array();
  $form['sample_value'] = array(
    '#type' => 'textfield',
    '#title' => 'Sample Value',
    '#size' => 20,
    '#maxlength' => 150,
    '#required' => TRUE,
  );

 //Make sure you set Drupal form submission to be false.

  $form['#executes_submit_callback'] = FALSE;

How to load a block programmatically and use in twig file

There might be a situation when you have to print a block at a specific location on the webpage. In that case, you can load the block and set up a variable which will be printed in twig file. This can be achieved by following way:

Add the following code in right preprocess in the .theme file.

  $block = Block::load('test_block');
  $variables['test_block'] = \Drupal::entityTypeManager()
    ->getViewBuilder('block')
    ->view($block);

Now in your twig file you print test block in following way {{ test_block }}.

How to load field collection programmatically in Drupal 8

Field collection can be used in case a field has subfields. For eg Name can have subfields such as First Name, Middle Name, and Last Name. There might be a requirement of loading field collection items programmatically. It can be done in following way:

$fieldCollection = \Drupal\field_collection\Entity\FieldCollectionItem::load($fieldCollectionId);
$firstName = $fieldCollection->get('field_first_name')->getValue();

It is better to use Paragraph module instead of using field collection, becuase it has better features and is being well maintained.

How to limit meta description of an article to 150 characters in Drupal 8

By default meta tag, module  use node summary/body token to populate meta description of the content type having body field. It does not follow the standard practice of meta description of length between 135 to 150 characters. Even if you set summary length between 135 and 150, your meta description might end with incomplete word and provide a bad search engine preview. You can create a custom token which meets both the criteria i.e 1. The length between 135 and 150 and  2. The last word might be incomplete because of the character limit. You can create a custom token in following way: