Skip to main content

How to programmatically create a custom Drupal 8 block

Blocks are a great way to add pieces or chunks of content to your Drupal site.  Capable of displaying simple text, images, forms or complex logic.  There are plenty of sites around that show you how to add a simple custom block.  However, if you are a developer like me, when you are writing your custom block programmatically it has far more requirements than a simple block.  In this article, I'll show how to:

Loading and accessing Drupal node data - like title, nid and other values

Loading the node

To query the node, I prefer to create a series of functions to mange the process in a class.  However, keeping this simple, this can be achieved through:

$node = \Drupal\node\Entity\Node::load($nid);

Otherwise if you require to load multiple nodes, where the list of node.nids is in an array.

$nodes = \Drupal::entityTypeManager()->getStorage('node');

Subscribe to Drupal 8.9.x