Monday 25 February 2019

Drupal 8 prevent caching of programmatically created block.

I was working on creating a custom block programmatically.

The requirement was to show the file uploaded to a specific node.

The problem was block was caching and showing same value for each node page.

After a lot of Google search for module hooks, theme hooks, I found that there is an inbuilt function in the block definition itself.

getCacheMaxAge()

This function can set cache age to 0 hence disabling to cache the block.

Final code:

<?php
/**
 * @file
 * Contains \Drupal\sample\Plugin\Block\XaiBlock.
 */
namespace Drupal\sample\Plugin\Block;
use Drupal\Core\Block\BlockBase;
//use GuzzleHttp\json_decode;
/**
 * Provides a 'article' block.
 *
 * @Block(
 *   id = "article_block",
 *   admin_label = @Translation("Article"),
 *   category = @Translation("Custom article block sample")
 * )
 */
class ArticleBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
public function build() {
$nid = NULL;
$content = NULL;
$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
// You can get nid and anything else you need from the node object.
$nid = $node->id();
}
if (! empty($nid)) {
$node = \Drupal\node\Entity\Node::load($nid);
$changedVal = $node->get('changed')->getValue();
$changedVal = ! empty($changedVal[0]['value']) ? $changedVal[0]['value'] : '';
if ($changedVal) {
$changedVal = date('d F Y', $changedVal);
}
$content .= '<p class="txt">Last updated ' . $changedVal . '</p>';
}
return array(
'#type' => 'markup',
'#markup' => $content
);
}
/**
     * {@inheritdoc}
     */
    public function getCacheMaxAge() { // <- This function disables block caching.
return 0;
    }
}

No comments:

Post a Comment

Parenting tips to inculcate learning habits in your kid

Parenting tips to inculcate learning habits in your kid Tip #1) Children do not learn things, they emitate. So, try to do things by yours...