Skip to main content

Snippets - Code for Drupal

Snippets

public function getCacheMaxAge() {
  // Disable block cache.
  return 0;
}
Disable cache of a custom block
See complete code
~/composer clear-cache
Clear the Composer cache
See complete code
$bid = 20 // Get the block id through config, SQL or some other means.
$block = \Drupal\block_content\Entity\BlockContent::load($bid); // Load block entity.
$render = \Drupal::entityTypeManager()->
  getViewBuilder('block_content')->view($block);
return $render;
How to display a block programmatically
See complete code
/**
 * Implements hook_post_update_NAME().
 */
function MODULE_post_update_api_data_value(&$sandbox) {

  if (!isset($sandbox['total'])) {
  // Get API Data content type nid's.
    $nids = Drupal::entityQuery('node')
      ->condition('type', 'apidata')
      ->execute();
    $sandbox['total'] = count($nids);
    $sandbox['current'] = 0;
  }

  $nodes_per_batch = 50;
  $nids = Drupal::entityQuery('node')
    ->condition('type', 'apidata')
    ->range($sandbox['current'], $nodes_per_batch)
    ->execute();

  foreach ($nids as $nid) {
    $node = Drupal::entityTypeManager()
      ->getStorage('node')
      ->load($nid);

	// Check if the field is empty.
    if (empty($node->field_api_target->value)) {
      // If is empty, set default value (0).
      $node->field_api_target->value = 0;
    }

    $node->save();
    $sandbox['current']++;
  }

  if ($sandbox['total'] === 0) {
    // Until it is finished, the batch does not stop.
    $sandbox['#finished'] = 1;
  }
  else {
    // Indicates the percentage of the completed.
    $sandbox['#finished'] = ($sandbox['current'] / $sandbox['total']);
  }
}
Post Update in Drupal
See complete code
drush eval "print_r(array_keys(entity_get_info()));"
Get complete list of Drupal entities
See complete code

Join the Drupal Sapiens Community

Save content that interests you, connect with others in the community, contribute to win prizes and much more.

Login or create an account here

Featured

Last news