Build a configurable block in Drupal 11
Last updated November 22, 2026
Learning outcome
A block you place through Drupal’s interface has two parts: reusable behavior supplied by a plugin, and settings saved for that particular placement. Understanding that separation is a useful first step into module development. It explains how one PHP class can supply several blocks with different messages, titles, regions, and visibility rules.
In this tutorial, you will build a Site notice block. A site builder can enter a message and choose whether to show the site name below it. The message belongs to the placement; the name comes from Drupal’s existing site configuration. Changing either should update the output through Drupal’s normal cache invalidation.
Prerequisites
Use a disposable local Drupal 11 site where you can edit module files, run Drush, and administer blocks. You should already understand PHP variables, arrays, functions, and basic Drupal site building. You will also need permission to change the practice site’s name for the cache exercise.
Tested environment and versions
The complete example was tested with Drupal 11.4.12, PHP 8.5.7, and Drush 13.8.0 with Drupal Code Generator 4.2.0, using core’s Stark theme. Your theme will determine the final appearance and available regions.
What you will learn
By the end, you should be able to explain how Drupal discovers a block plugin, add settings to its placement form, describe those settings with configuration schema, obtain an existing service through dependency injection, and return safely rendered, cacheable output.
The finished module contains three files. Drupal supplies the block management screens, placement storage, form processing, and rendering pipeline.
For an ordinary notice that editors need to maintain as content, start by considering a core content block. This exercise deliberately uses a plugin to teach module development and to combine placement settings with information obtained from a Drupal service. Choosing a plugin also makes these messages configuration: they can travel with a site’s configuration deployment.
Prepare a practice site
Run the commands from the Composer project root, where composer.json and vendor/ live. The example assumes the public document root is web/; adjust that directory if your project uses another layout. In Lando, use lando drush in place of vendor/bin/drush, and lando php in place of php, so commands run inside the project’s PHP environment.
Confirm that Drush bootstraps the intended practice site:
vendor/bin/drush status --fields=drupal-version,uri,bootstrap
Check the version and site URI, and look for a successful bootstrap before continuing. Keep the site’s caches enabled. Later, you will use caching behavior as a test of the block’s correctness.
Generate the module skeleton
Start with the generators provided by the project’s Drush installation. They create the standard file layout and boilerplate, leaving you to implement the block’s behavior. From the Composer project root, run:
vendor/bin/drush generate module
Use these answers when prompted:
| Prompt | Answer |
|---|---|
| Module name | Learning Notice |
| Module machine name | learning_notice |
| Module description | Provides a configurable site notice block for a module development tutorial. |
| Package | Learning |
| Dependencies | drupal:block |
| Create module file | No |
| Create install file | No |
| Create README.md file | No |
The generator creates web/modules/custom/learning_notice/learning_notice.info.yml. Open it and check the name, machine-name-based filename, and dependency. The tested generator starts with core_version_requirement: ^10 || ^11; change that line to ^11 so this example advertises the major version being taught and tested. The completed file is:
name: 'Learning Notice'
type: module
description: 'Provides a configurable site notice block for a module development tutorial.'
package: Learning
core_version_requirement: ^11
dependencies:
- drupal:block
The directory and filename use the module’s machine name, learning_notice. The human-readable name can contain spaces. type: module identifies the extension type, and the dependency tells Drupal to install core’s Block module when this module is installed.
We declined the optional .module and .install files because this example has no procedural hooks or installation tasks to implement. Generating unused files would add nothing to the lesson.
Enable the new module on your practice site:
vendor/bin/drush en learning_notice -y
At this point the module is installed, but it does not provide a block yet. Generating files, enabling a module, and placing a block are separate steps. Drush documents the module generator.
Generate a configurable block
Run the block-plugin generator:
vendor/bin/drush generate plugin:block
Use these choices:
| Prompt | Answer |
|---|---|
| Module machine name | learning_notice |
| Block admin label | Site notice |
| Plugin ID | learning_notice |
| Plugin class | LearningNoticeBlock |
| Block category | Learning |
| Make the block configurable | Yes |
| Inject dependencies | Yes |
| Service name | config.factory |
| Next service name | Press Enter with no value to finish choosing services |
| Create access callback | No |
Enter the plugin ID explicitly: the suggested default is learning_notice_site_notice, while this example uses learning_notice. After entering config.factory, the service question repeats so that you can add more dependencies; the empty response ends that list.
Choosing a configurable block adds configuration methods and a schema file. Choosing dependency injection adds the constructor, factory method, interface, and service argument. We do not need a custom access callback for this public notice. Drupal’s existing placement, visibility, and access handling remain in place. Drush documents the block generator.
You should now have:
learning_notice/
├── learning_notice.info.yml
├── config/
│ └── schema/
│ └── learning_notice.schema.yml
└── src/
└── Plugin/
└── Block/
└── LearningNoticeBlock.php
Open the generated class and schema before editing them. The class contains an Example configuration field and an It works! render result. The schema describes that example setting. The generator has supplied the extension points; it cannot infer the notice message, checkbox, or cache dependency required by this lesson.
Implement the notice behavior
Keep the generated construction code and replace the sample settings and output with the completed implementation below in web/modules/custom/learning_notice/src/Plugin/Block/LearningNoticeBlock.php. The changes are the message and checkbox, the configuration read during rendering, and its cacheability metadata. As you compare the files, identify which parts were generated and which express the notice’s behavior.
<?php
declare(strict_types=1);
namespace Drupal\learning_notice\Plugin\Block;
use Drupal\Core\Block\Attribute\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides a site notice block.
*/
#[Block(
id: 'learning_notice',
admin_label: new TranslatableMarkup('Site notice'),
category: new TranslatableMarkup('Learning'),
)]
final class LearningNoticeBlock extends BlockBase implements ContainerFactoryPluginInterface {
/**
* Constructs the plugin instance.
*/
public function __construct(
array $configuration,
$plugin_id,
$plugin_definition,
private readonly ConfigFactoryInterface $configFactory,
) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition): self {
return new self(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('config.factory'),
);
}
/**
* {@inheritdoc}
*/
public function defaultConfiguration(): array {
return [
'message' => 'Check our opening hours before visiting.',
'show_site_name' => TRUE,
];
}
/**
* {@inheritdoc}
*/
public function blockForm($form, FormStateInterface $form_state): array {
$form['message'] = [
'#type' => 'textfield',
'#title' => $this->t('Notice message'),
'#description' => $this->t('Enter plain text. HTML will be displayed literally.'),
'#default_value' => $this->configuration['message'],
'#required' => TRUE,
];
$form['show_site_name'] = [
'#type' => 'checkbox',
'#title' => $this->t('Show the site name'),
'#default_value' => $this->configuration['show_site_name'],
];
return $form;
}
/**
* {@inheritdoc}
*/
public function blockSubmit($form, FormStateInterface $form_state): void {
$this->configuration['message'] = $form_state->getValue('message');
$this->configuration['show_site_name'] = (bool) $form_state->getValue('show_site_name');
}
/**
* {@inheritdoc}
*/
public function build(): array {
$build['message'] = [
'#type' => 'container',
'text' => ['#plain_text' => $this->configuration['message']],
];
if ($this->configuration['show_site_name']) {
$site = $this->configFactory->get('system.site');
$build['site_name'] = [
'#type' => 'container',
'text' => ['#plain_text' => $site->get('name')],
];
CacheableMetadata::createFromObject($site)->applyTo($build);
}
return $build;
}
}
The namespace connects the module to its class directory. Drupal maps Drupal\learning_notice to this module’s src/ directory. The remaining Plugin\Block segments match src/Plugin/Block/. The class name matches the filename, including capitalization. You do not add a separate Composer autoload entry for this module namespace.
The use statements give names to the Drupal and Symfony classes used below. For example, Block in the attribute refers to Drupal’s block-plugin attribute class. It is metadata attached to the PHP class, rather than a function call that places a block on a page.
The attribute supplies the stable plugin ID, learning_notice, and the label and category shown in the block library. Drupal’s block manager discovers classes in this plugin directory and reads their attributes. BlockBase provides the standard block-plugin behavior; our class overrides the methods involved in its settings and output. Drupal’s block-plugin guide explains the discovery seam.
The plugin ID and module machine name happen to match in this example. They are separate identities: a module can supply several block plugins, each with its own ID.
Describe the settings with schema
Replace the generated example mapping in web/modules/custom/learning_notice/config/schema/learning_notice.schema.yml with the notice settings and constraints below:
block.settings.learning_notice:
type: block_settings
label: 'Site notice block settings'
constraints:
FullyValidatable: ~
mapping:
message:
type: label
label: 'Notice message'
constraints:
NotBlank: []
show_site_name:
type: boolean
label: 'Show the site name'
The key is block.settings. followed by the plugin ID. Core uses that ID to select the schema for the settings inside a saved block placement. Extending block_settings retains the description of standard settings, including the block label. The mapping adds our message and checkbox.
label describes a short, translatable string; boolean describes the on/off choice. The NotBlank constraint expresses the requirement for a message when this configuration is validated. FullyValidatable opts this settings mapping into Drupal’s full validation rules. These are Drupal’s schema and validation mechanisms; the module does not need a separate settings validator.
Schema describes the data. It does not save a placement or populate the form. Those responsibilities belong to the block entity and plugin methods. It also gives the configuration translation system information about translatable values, although setting up translations is a separate site-building task. Read more about configuration schema and its types.
Rebuild discovery and place your first notice
The module is already enabled. Rebuild discovery caches after customizing the generated class and schema:
vendor/bin/drush cr
In Drupal:
- Open Structure → Block layout at
/admin/structure/block. - Select your active front-end theme and choose Place block for a visible region.
- Find Site notice in the block library and choose Place block beside it.
- Set its title to First notice, leave the title displayed, and enter Check our opening hours before visiting. as the notice message.
- Leave Show the site name checked. For this exercise, leave visibility unrestricted.
- Save the block, then visit a normal public page that renders the chosen region.
You should see the title, your message, and the practice site’s name. Open the same page in a logged-out browser session and check the result there too.
The region belongs to the theme, so there is no universal region name to put in this procedure. If the block is missing, first check that the placement is enabled, belongs to the theme you are viewing, and uses a region rendered on that page.
Follow a setting from form to page
There are two different kinds of saved information involved:
| Information | Owner | Example |
|---|---|---|
| Plugin implementation | Module code | LearningNoticeBlock.php |
| One placement and its settings | Block configuration entity | Its message, checkbox, region, and visibility |
| Site-wide information | Existing simple configuration | The name in system.site |
Placing the plugin creates a block configuration entity. It references the plugin ID and stores that placement’s settings. Drupal can then create a plugin instance using those settings whenever it needs the block.
The main connections are:
- Drupal discovers the module class and its Block attribute through the block plugin manager.
- The manager constructs a plugin instance using the saved placement settings and the injected configuration factory.
- The block configuration form updates the saved settings for that placement.
- The plugin’s build method returns a render array.
- Drupal renders the placed block through its normal rendering pipeline.
This sequence separates discovery, saved configuration, and rendering. Finding a plugin in the library does not automatically put it on the page: the placement supplies the theme, region, and settings.
Defaults supply a starting point
defaultConfiguration() returns the initial values for our two settings. BlockBase combines the standard block defaults, the plugin’s defaults, and the configuration passed to that instance. Saved values take precedence over defaults. The merge is visible in core’s configuration implementation.
That precedence matters during development. Changing the default message in PHP will not replace a message already saved for a placement. The saved configuration remains the source of that placement’s value. If you need to change an existing notice, edit its settings through Drupal.
Form API defines the controls
blockForm() adds two elements to Drupal’s existing block configuration form. Keys beginning with # are Form API properties: #type selects an element, #title supplies its label, and #default_value fills it with the current setting.
#required asks the normal form-validation system to require a message. blockSubmit() receives the submitted values after successful validation and updates the plugin configuration. Drupal’s surrounding block form then saves the placement. Calling the plugin’s method alone would not be a substitute for saving the block entity.
The checkbox value is cast to a PHP boolean because the setting represents an on/off choice. The field names in blockForm() and blockSubmit() match. A spelling mismatch between those methods can produce a control that appears correctly but never saves the intended value. The block form documentation describes these extension methods.
Try this now: edit First notice, change the message to The workshop starts at 11., uncheck Show the site name, and save. Reopen the configuration form. Both values should remain as you saved them. On the public page, the new message should appear without the site name below it.
Each placement gets its own values
Place Site notice a second time. Give this placement the title Second notice, enter The workshop starts at 10., and leave its site-name checkbox checked.
Visit the page again. The first notice should still say 11, while the second says 10. One class supplies the behavior, and two block configuration entities supply different settings. Editing the second should leave the first unchanged.
This is why our submit method writes to $this->configuration. Writing the message to one global settings object would give the notices a shared value, changing the requirement from per-placement settings to site-wide settings.
Obtain an existing service through injection
The site name is already stored in system.site. The block needs a configuration factory to read it. Rather than looking up a global dependency inside build(), the constructor declares a ConfigFactoryInterface dependency.
The first three constructor arguments are the configuration, plugin ID, and plugin definition used by the block system. Passing them to the parent constructor preserves that initialization. The fourth is our extra dependency.
The generated promoted property, private readonly ConfigFactoryInterface $configFactory, accepts the object and stores it on the instance. This is PHP constructor property promotion; it saves writing a separate property declaration and assignment. readonly prevents assigning a different value to that property after construction; it does not make the configuration factory itself immutable.
Drupal’s plugin factory recognizes ContainerFactoryPluginInterface and calls the static create() method. That method obtains core’s existing config.factory service and passes it to the constructor. The factory is the connection point to the service container; the rest of the class works with its declared dependency. The interface documents this construction contract.
There is no module-owned .services.yml file because we are consuming an existing service, not defining a new one. Constructor injection also makes the dependency visible to someone reading or testing the class.
Inside build(), get('system.site') obtains the configuration object, and get('name') reads its name value. The block reads that value when it builds; it does not copy the site name into each placement’s saved settings.
Return output through the Render API
build() returns a render array: a description of what Drupal should render. It leaves the conversion to HTML to Drupal’s rendering pipeline.
The top-level keys message and site_name are children. Each uses the container render element to provide a wrapper. Its text child uses #plain_text, which tells Drupal to escape the value as text. The result displays characters such as < and & literally. Drupal’s renderer implements that plain-text handling.
Test the distinction. Set one notice’s message to:
Bring <em>notes</em> & questions.
The angle brackets and em tags should appear in the notice. The word notes should not become italicized by that input. This block accepts plain text, as its form description promises.
The static form labels use $this->t(), and the plugin attribute uses TranslatableMarkup. Those strings belong to the interface. The site builder’s message is configuration data described by schema. Passing arbitrary entered messages to $this->t() is not the configuration translation workflow.
If you need editor-authored rich text, a formatted-text content block is a useful starting point. Changing #plain_text to #markup would change the input/output contract; it would not by itself provide text-format selection and its associated processing.
Keep the block correct when cached
Enable Show the site name on the first notice again. Load the public page, then reload it so Drupal has an opportunity to serve cached output.
Now change the practice site’s name under Configuration → System → Basic site settings at /admin/config/system/site-information. Save and return to the public page in the logged-out browser. The name inside the notice should update without running drush cr.
The important line is:
CacheableMetadata::createFromObject($site)->applyTo($build);
Reading a configuration value gives the PHP code the current name. Associating its cacheability metadata with the render array also tells Drupal which data the output depends on. The system.site object supplies the config:system.site cache tag. Saving that configuration invalidates cached output carrying the tag. Core’s metadata helper obtains the dependency’s cacheability information.
For this block, consider three different questions:
| Question | Cache mechanism | This example |
|---|---|---|
| What changing data makes this output stale? | Tags | The displayed site name depends on system.site. |
| Which request dimensions produce different output? | Contexts | This implementation adds no user-specific or request-specific variation. |
| Does the output expire after a period of time? | Maximum age | No time-based expiry is needed here. |
Drupal’s block rendering also carries the saved placement’s cacheability information, so changing its message invalidates the relevant output. The plugin adds the dependency it introduces by reading site configuration. Its metadata joins the surrounding render tree. The cacheability guide explains how metadata participates in rendering.
The site configuration dependency is attached only when its name is included in the output. There is no need to set a zero maximum age. Doing so would avoid reusing the block’s output instead of expressing what makes it stale.
These settings are intended for public notices. If a later block displays restricted information or varies by account, work through its access and cache-context requirements separately. A placement’s visibility options do not make arbitrary data safe to disclose.
Inspect what Drupal saved
Open a placement’s configuration form and look at its URL. The final segment after /admin/structure/block/manage/ is that placement’s machine name. It is distinct from the reusable plugin ID.
For a placement whose machine name is learning_notice_first, run:
vendor/bin/drush config:get block.block.learning_notice_first settings
Substitute your actual placement’s machine name. Within the settings, you should find the plugin ID, message, and boolean choice. For example, this excerpt shows a message with the site-name option enabled:
id: learning_notice
message: 'Bring <em>notes</em> & questions.'
show_site_name: true
Export and review the placement
Use your practice project's existing configuration workflow. Drush reads the synchronization directory from the site's settings; inspect that location and the differences between active and exported configuration before exporting:
vendor/bin/drush status --fields=config
vendor/bin/drush config:status
vendor/bin/drush config:export
Confirm the export when prompted, then review the complete Git diff in the reported synchronization directory. The block.block.PLACEMENT_NAME.yml files describe each placement's theme, region, plugin ID, and settings. Enabling the module also changes core.extension.yml. The module's schema describes how Drupal interprets settings; it does not contain the saved placements.
A full export can include unrelated site changes. Keep only the intentional changes in the reviewed deployment. Module code and exported configuration travel together through the project's normal deployment process. Copying PHP alone will not recreate the placements.
On another environment of the same site, the standard import command reads its synchronization directory and asks you to confirm the proposed changes:
vendor/bin/drush config:import
Configuration synchronization expects matching site UUIDs. Follow the project's deployment procedure for module code and configuration, then inspect the placement with config:get and visit the rendered page. A successful import alone does not prove the block works. Drush documents export and import.
Diagnose a broken checkpoint
| Symptom | Check |
|---|---|
| Learning Notice is absent from Extend | Match the module directory and .info.yml filename; validate YAML indentation and the core requirement. |
| The enabled module has no Site notice plugin | Check src/Plugin/Block/, namespace, class filename, the Block import and attribute; rebuild discovery caches. |
| PHP reports too few constructor arguments | Check both ContainerFactoryPluginInterface and create(); the factory must supply the fourth argument. |
| Values revert after saving | Match the form-element keys, submitted keys, and configuration keys; confirm you are reopening the same placement. |
| An edited default has no visible effect | Inspect the placement’s saved value, which takes precedence over the default. |
| Output is absent | Check the active theme, enabled placement, region, and visibility; test the public page as a logged-out visitor. |
| Site name stays stale until caches are rebuilt | Check the dependency metadata, then retest with caches enabled; repeated cache rebuilds conceal the behavior you need to verify. |
For PHP syntax errors, run the check in your project’s PHP environment:
php -l web/modules/custom/learning_notice/src/Plugin/Block/LearningNoticeBlock.php
Use Drupal’s logs for the actual error if the page fails. Rebuilding caches will not fix invalid PHP, an incorrect namespace, or a missing constructor argument.
Apply the pattern with less guidance
Add an optional Show the site slogan checkbox. Keep the existing site-name checkbox independent. Before editing, write down the places this new setting must pass through: default value, form element, submit handler, schema, and rendered output.
The slogan already belongs to system.site, so the existing injected configuration factory can read it. Decide when its dependency metadata needs to be attached, including the combination where the site name is hidden but the slogan is shown. Display the slogan as plain text.
Check your work with two placements using different checkbox combinations. Change the slogan through Drupal, then confirm the visible slogan updates with caches enabled. Leave the slogan empty and decide whether omitting its empty wrapper would make the output clearer. This extension is your exercise; the three-file example above is the completed site-name version.
When you finish, restore the practice site's original name. Remove the example placements through Block layout, or uninstall the example module through Extend → Uninstall. The equivalent Drush command on your practice site is:
vendor/bin/drush pm:uninstall learning_notice
Review the dependent configuration listed by Drush before confirming. Uninstalling removes the module's placements and their settings. Keep its files available until Drupal finishes uninstalling; remove the custom module directory afterward if you no longer need it. Drush documents module uninstallation.
Example files
Learning Notice example module
The archive contains the three module files and a README with setup instructions and the example’s verification scope.