
Step-by-Step Guide to Creating Blocks in Drupal Programmatically
Introduction
When it comes to Drupal web development, blocks play an essential role in managing and displaying content across your website. Blocks are reusable components that can contain text, media, menus, or even dynamic PHP-driven content. While Drupal’s admin interface allows you to create blocks easily, many enterprises and developers prefer creating blocks programmatically for better control, reusability, and automation.
As a Drupal web agency, we often recommend programmatic block creation when working with custom modules, multi-site environments, or when building complex Drupal projects. In this blog, we’ll provide a step-by-step guide to creating blocks in Drupal programmatically, explain best practices, and highlight why this approach can give your business an edge.
Why Create Blocks Programmatically in Drupal?
Before diving into the technical steps, let’s understand the benefits of creating Drupal blocks programmatically:
- Reusability: Easily move blocks between environments without manual setup.
- Version Control: Blocks can be tracked and managed in Git or other version control systems.
- Performance: Optimized rendering with caching strategies.
- Automation: Reduce manual work by defining blocks once and deploying them across multiple sites.
- Consistency: Ensures all environments (dev, staging, production) have identical block configurations.
For businesses, programmatically creating blocks means fewer errors, faster development cycles, and a more scalable Drupal solution.
Step 1: Create a Custom Module
To create a block programmatically, you’ll need a custom module.
- Navigate to your Drupal installation’s
modules/custom/
directory. Create a new folder for your module, for example:
mkdir modules/custom/custom_block_example
- Inside this folder, create two essential files:
custom_block_example.info.yml
custom_block_example.module
Example: custom_block_example.info.yml
name: Custom Block Example
type: module
description: 'A custom module to create a block programmatically in Drupal.'
core_version_requirement: ^10 || ^11
package: Custom
dependencies:
- drupal:block
This file tells Drupal about your module and ensures it works with Drupal 10 and 11.
Step 2: Create the Block Plugin
Drupal’s block system is powered by plugins. To create a block programmatically, you need to define a plugin class.
Inside your module folder, create this path:
modules/custom/custom_block_example/src/Plugin/Block/
- Create a file named
CustomBlock.php
.
Example: CustomBlock.php
<?php
namespace Drupal\custom_block_example\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Provides a 'Custom Block Example' block.
*
* @Block(
* id = "custom_block_example",
* admin_label = @Translation("Custom Block Example"),
* category = @Translation("Custom")
* )
*/
class CustomBlock extends BlockBase {
/**
* {@inheritdoc}
*/
public function build() {
return [
'#markup' => $this->t('Hello, this is a custom block created programmatically!'),
];
}
}
In this code:
id
: Unique identifier for the block.admin_label
: Name shown in Drupal’s block admin interface.category
: Category for grouping blocks.build()
: Defines what the block displays.
Step 3: Add Configuration Options (Optional)
Sometimes, you want your block to be configurable (e.g., customizable text, images, or links). You can add configuration forms to your block.
Update the CustomBlock.php
with these methods:
/**
* {@inheritdoc}
*/
public function blockForm($form, FormStateInterface $form_state) {
$form['custom_text'] = [
'#type' => 'textfield',
'#title' => $this->t('Custom Text'),
'#default_value' => $this->configuration['custom_text'] ?? '',
];
return $form;
}
/**
* {@inheritdoc}
*/
public function blockSubmit($form, FormStateInterface $form_state) {
$this->configuration['custom_text'] = $form_state->getValue('custom_text');
}
/**
* {@inheritdoc}
*/
public function build() {
$custom_text = $this->configuration['custom_text'] ?? $this->t('Default text');
return [
'#markup' => $this->t('@text', ['@text' => $custom_text]),
];
}
Now, when placing the block in the Drupal admin, users can add custom text.
Step 4: Enable Your Module
Once your block is ready, enable your module:
drush en custom_block_example -y
Or through the Drupal admin UI:
- Navigate to Extend.
- Find Custom Block Example.
- Enable it.
After enabling, your custom block will appear under Structure → Block layout.
Step 5: Place the Block
- Go to Structure → Block layout.
- Choose a region (e.g., Sidebar first, Content, Footer).
- Find Custom Block Example in the list.
- Place it in your desired region.
Your programmatically created block should now be visible on your site!
Best Practices for Programmatic Blocks in Drupal
When creating blocks programmatically, follow these Drupal best practices:
Use Cache Wisely – Always set cache contexts, tags, and max-age to improve performance.
return [ '#markup' => $this->t('Dynamic Block'), '#cache' => [ 'max-age' => 0, ], ];
- Organize Code Properly – Keep block plugins in
src/Plugin/Block
for clarity. - Use Dependency Injection – Instead of static services, inject dependencies for maintainability.
- Keep It Reusable – Write blocks with configuration options so they can be reused across projects.
- Follow Drupal Coding Standards – Run
phpcs
with the Drupal standard for clean, maintainable code.
When Should Businesses Use Programmatic Blocks?
From a business perspective, programmatic blocks are highly useful when:
- Running multi-site Drupal installations that need consistent block setups.
- Automating deployment pipelines with DevOps.
- Building enterprise-level Drupal applications where scalability and maintainability are crucial.
- Creating custom Drupal solutions like dashboards, user-specific blocks, or API-driven content.
This approach ensures your Drupal website development remains professional, future-proof, and aligned with industry standards.
Conclusion
Creating blocks programmatically in Drupal is a powerful way to build reusable, scalable, and easily maintainable components for your website. For developers, it ensures clean workflows and automation; for businesses, it translates into efficiency, scalability, and reduced maintenance costs.
As a Drupal web agency, we specialize in building high-performance, future-ready Drupal solutions tailored to your business needs. Whether you need custom block development, Drupal theming, or enterprise-level support, our team can help you leverage Drupal’s full potential.
✅ Looking to enhance your Drupal website with custom features?
Get in touch with our expert Drupal developers today and let’s create a scalable, secure, and powerful solution for your business.