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 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: