Create block in Drupal module programmatically
Blocks in Drupal 8 are instances of the block plugin.
The Drupal Block Manager scans your modules for classes containing the @Block annotation.
The example below uses the @Block
annotation with the properties id
and admin_label
to define a custom block.
Create the file src/Plugin/Block/HelloBlock.php
inside the skeleton module you previously created, and add the code shown below.
For your Drupal site to recognize this new class, you need to clear the cache.
<?php namespace Drupal\hello_world\Plugin\Block; use Drupal\Core\Block\BlockBase; /** * Provides a 'Hello' Block. * * @Block( * id = "hello_block", * admin_label = @Translation("Hello block"), * category = @Translation("Hello World"), * ) */ class HelloBlock extends BlockBase { /** * {@inheritdoc} */ public function build() { return [ '#markup' => $this->t('Hello, World!'), ]; } }
To add the “Hello block,” go to Structure → Block Layout (admin/structure/block
) and click the “Place block” button next to any available region.
Clicking “Place block” will open a dialog listing all available blocks. To quickly find your block, use the “Filter by block name” option or scroll to locate the “Hello block.” This way, you can add as many instances of the custom block as you like to different areas of your site.
Troubleshooting
- The class name and file name must match (e.g.,
HelloBlock
and/src/Plugin/Block/HelloBlock.php
). If the class name differs, the block may appear in the list, but it cannot be added. - Always double-check all paths and file names. Your
.php
file must be in the correctly named directory (/src/Plugin/Block/
), or it will not be discovered by Drupal. - If your block fails to render without visible errors or watchdog entries, check the PHP/Apache error logs.
- If your block doesn't appear in the list, make sure to rebuild Drupal caches (e.g., with
drush cr
). - Ensure your module's machine name is all lowercase. Some users report that blocks don’t appear for modules using camelCase naming. For example,
myModule
will not show defined blocks, butmy_module
will. This behavior was confirmed as of Drupal 8.8.1.
Note: Using Twig Templates with Custom Blocks
1. Add a hook_theme implementation in your .module file.
Note: Do not name the theme function as block__...
— it won’t pass any variables to Twig templates. Instead, use your module’s name as the prefix.
2. Use #theme
in the render array within the build()
method, and pass variables at the same level using #varname
.
Drupal’s online documentation is © 2000-2020 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License.