Example 2: Placing a block¶
A placed block becomes one resource, block.placement, with create, update and delete operations. Its settings key holds whatever the chosen block plugin takes. A plugin that declares its structure is placed through that structure (rung 2). A plugin with only config schema has its structure read from that schema and is placed the same way, with no change to the plugin (rung 0).
Today¶
A placed block is the config entity block.block.<id>, and each plugin describes its own settings. Core's branding block describes its three settings, whether to show the logo, the site name and the slogan, in three places: the block.settings.system_branding_block config schema gives types and labels, defaultConfiguration() gives defaults, and blockForm() gives other labels and descriptions. Only the block form uses them. Core has no Tool API tool that places a block and checks its settings.
The resource, added once¶
The module that owns block placement adds the resource; in core that is the block module. It names the block config entity as its storage, the machine name as its identity, and its operations: create, update and delete, with a read added beside them. Update and delete take only the machine name. The storage loads the block by it, refuses a name that names no block, and holds the theme to the one the block is in. Each asks "administer blocks", the permission core's block layout asks today:
#[Resource('block.placement',
label: new TranslatableMarkup('Placed block'),
description: new TranslatableMarkup('A block placed in a region of a theme under a machine name: its label, the settings its plugin takes, its weight, its status and when it shows.'),
identity: ['id'],
storage: BlockPlacementResourceStorage::class,
)]
#[Operation('create',
label: new TranslatableMarkup('Place a block'),
description: new TranslatableMarkup('Places a block under a machine name the caller chooses, in a region of a theme, with the settings its plugin takes; a machine name already in use is refused.'),
permission: self::PERMISSION,
creates: TRUE,
idempotent: TRUE,
)]
final class BlockPlacementResource implements ResourceInterface {
/**
* The permission every operation asks: the block layout's.
*/
public const PERMISSION = 'administer blocks';
/**
* Edits a placed block, named by its machine name, in its own theme.
*
* Moving a block to another theme is not offered: the placement
* storage holds the theme to the one the block is in, read off the
* block it loads by the machine name (heldToEntity()).
*/
#[Operation('update',
label: new TranslatableMarkup('Edit a placed block'),
description: new TranslatableMarkup('Changes a placed block, named by its machine name: its label, region, weight, status, plugin settings and visibility. Its theme stays as it is.'),
permission: self::PERMISSION,
)]
public static function update(string $id): OperationContext {
return new OperationContext(known: ['id' => $id]);
}
/**
* Removes a placed block, named by its machine name.
*/
#[Operation('delete',
label: new TranslatableMarkup('Remove a placed block'),
description: new TranslatableMarkup('Removes a placed block, named by its machine name, from its region.'),
permission: self::PERMISSION,
destructive: TRUE,
deletes: TRUE,
)]
public static function delete(string $id): OperationContext {
return new OperationContext(known: ['id' => $id]);
}
Its input is every key a placed block has: label, machine name, whether the label shows, the plugin, the plugin's settings, theme, region, weight, status and visibility conditions. The settings key depends on the chosen plugin:
public static function defineInputs(BlueprintInterface $inputs): void {
$inputs->add('label', Schema::string()->minLength(1)
->title(t('Title'))
->description(t('The title of the block as shown to the user.'))
->maxLength(255)
->check('drupal:Regex', [
'pattern' => '/([^\PC])/u',
'match' => FALSE,
'message' => t('The title may not span lines or hold control characters.'),
])
->required());
$inputs->add('id', Schema::string()->minLength(1)
->title(t('Machine name'))
->description(t('A unique name for the placed block: lowercase letters, numbers, underscores and periods, not starting with a period.'))
->maxLength(166)
->check('drupal:Regex', [
'pattern' => '/^(?!\.)[a-z0-9_.]+$/D',
'message' => t('The machine name may hold only lowercase letters, numbers, underscores and periods, and may not start with a period.'),
])
->required());
$inputs->add('label_display', Schema::bool()
->title(t('Display title'))
->description(t('Whether the title is shown above the block.'))
->default(TRUE));
$inputs->add('plugin', Schema::string()
->title(t('Block'))
->description(t('What the block shows: a block plugin the block layout offers. A block that reads a context, such as the node of the page, is not offered yet.'))
->required());
$inputs->add('settings', Schema::object()
->title(t('Settings'))
->description(t('The settings of the block chosen, as its plugin declares them.'))
->annotation('x-surface-variants', ['by' => 'plugin', 'from' => BlockPluginStructures::class]));
$inputs->add('theme', Schema::string()->minLength(1)
->title(t('Theme'))
->description(t('The theme the block is placed in.'))
->check('drupal:ExtensionExists', ['type' => 'theme'])
->required());
// A region of any installed theme, until the theme narrows it to its
// own: every door offers a list before a theme is chosen.
$inputs->add('region', Schema::string()->minLength(1)
->title(t('Region'))
->description(t('The region of the theme the block is shown in.'))
->check('drupal:SurfaceAnyThemeRegion')
->required());
$inputs->add('weight', Types::weight()
->title(t('Weight'))
->description(t('The order of the block in its region: lighter blocks are shown first.'))
->default(0));
$inputs->add('status', Schema::bool()
->title(t('Enabled'))
->description(t('Whether the block is shown at all.'))
->default(TRUE));
$inputs->add('visibility', Schema::list(Schema::of('block.placement.condition'))
->title(t('Visibility'))
->description(t('The conditions the block is shown under, each at most once; with none, it is shown on every page.')));
}
plugin gets its choices from the settings variants: the block plugins the layout offers, each under its admin label.
The regions offered depend on the theme chosen:
#[RefinesInput('region')]
public static function regionsOfTheme(string $theme): Schema {
return Schema::any()->check('drupal:SurfaceThemeRegion', ['theme' => $theme]);
}
x-surface-variants names the class that gives each plugin's structure. A plugin that declares a structure gets it. Any other plugin gets the structure read from its config schema, block.settings.<plugin id>, with the plugin's defaults laid over it:
foreach ($definitions as $id => $definition) {
$label = $definition['admin_label'] ?? $id;
$structure = $definition[UsesStructure::DEFINITION_KEY] ?? NULL;
if (is_string($structure) && $structure !== '') {
$list->add($id, $label, structure: $structure);
continue;
}
$type = $this->reader->determine('block.settings.' . $id) ?? self::FALLBACK;
$defaults = $this->defaults($id);
$this->read[] = [$type, $defaults];
$list->add($id, $label, structure: $this->reader->structure($type, '', self::FALLBACK, $defaults));
}
No block plugin changes for this.
A block with only config schema¶
Core's branding block is not touched. The resource's served schema shows what is read:
"config_schema:block.settings.system_branding_block:own": {
"title": "config_schema:block.settings.system_branding_block:own",
"type": "object",
"properties": {
"use_site_logo": {
"title": "Use site logo",
"type": "boolean",
"default": true
},
"use_site_name": {
"title": "Use site name",
"type": "boolean",
"default": true
},
"use_site_slogan": {
"title": "Use site slogan",
"type": "boolean",
"default": true
}
},
"additionalProperties": false,
"required": [
"use_site_logo",
"use_site_name",
"use_site_slogan"
]
},
The types and labels come from config schema, the defaults from defaultConfiguration(). The labels and descriptions in blockForm() are not read, because they live in PHP that nothing else can read. That is enough to place the block and check its settings.
An example of what the list of block plugins might look like. surface_component, explained below, declares its structure; each of the others is read from config schema, and names the schema it came from:
"x-surface": {
"dependsOn": [
"plugin"
],
"by": "plugin",
"variants": {
"local_actions_block": "#/$defs/config_schema:block.settings.*:own",
"local_tasks_block": "#/$defs/config_schema:block.settings.local_tasks_block:own",
"page_title_block": "#/$defs/config_schema:block.settings.*:own",
"surface_component": "#/$defs/block.surface_component",
"system_branding_block": "#/$defs/config_schema:block.settings.system_branding_block:own",
"system_breadcrumb_block": "#/$defs/config_schema:block.settings.*:own",
"system_clear_cache_block": "#/$defs/config_schema:block.settings.*:own",
"system_main_block": "#/$defs/config_schema:block.settings.*:own",
"system_menu_block:account": "#/$defs/config_schema:block.settings.system_menu_block:*:own",
"system_menu_block:admin": "#/$defs/config_schema:block.settings.system_menu_block:*:own",
"system_menu_block:footer": "#/$defs/config_schema:block.settings.system_menu_block:*:own",
"system_menu_block:main": "#/$defs/config_schema:block.settings.system_menu_block:*:own",
"system_menu_block:tools": "#/$defs/config_schema:block.settings.system_menu_block:*:own",
"system_messages_block": "#/$defs/config_schema:block.settings.*:own",
"system_powered_by_block": "#/$defs/config_schema:block.settings.*:own",
"user_login_block": "#/$defs/config_schema:block.settings.*:own"
}
A block that declares its structure¶
As an example, take a block that lets a site builder place a component. They choose one of the site's single-directory components, such as a card or a banner, and fill in its props and slots. The proof of concept has such a block, surface_component, in its example module surface_examples_component_block.
Each component has its own props and slots, and which components exist depends on the site. Config schema written with the block cannot list them, so it leaves both unchecked:
block.settings.surface_component:
type: block_settings
label: 'Component block settings'
mapping:
component:
type: string
label: 'Component'
nullable: true
# Which components a site has is the site's, so no schema written once
# can name their props: the variant the component chooses holds them
# to its own keys before anything is written.
props:
type: ignore
label: 'Props'
# The same for the slots: the variant the component chooses holds them
# to its slots, and each nested component to its own.
slots:
type: ignore
label: 'Slots'
So the plugin declares a structure in which the props and slots depend on the component chosen:
#[Structure('block.surface_component')]
final class ComponentBlockStructure implements StructureInterface {
/**
* {@inheritdoc}
*/
public static function defineInputs(BlueprintInterface $inputs): void {
$inputs->add('component', Schema::string()
->title(t('Component')));
$inputs->add('props', Schema::object()
->title(t('Props'))
->annotation('x-surface-variants', ['by' => 'component', 'from' => ComponentProps::class]));
$inputs->add('slots', Schema::object()
->title(t('Slots'))
->annotation('x-surface-variants', ['by' => 'component', 'from' => ComponentSlots::class]));
}
and names it on the plugin class:
#[Block(
id: self::ID,
admin_label: new TranslatableMarkup('Component'),
)]
#[UsesStructure(ComponentBlockStructure::class)]
final class ComponentBlock extends TypedBlockBase implements ContainerFactoryPluginInterface {
A plugin class can also be its own structure: #[UsesStructure] with no argument, and defineInputs() on the plugin class itself. The proof of concept's example field formatter is written that way. A separate structure class, as here, is for a structure used in more than one place, where another plugin or a resource names the same class.
The placement resource places it with no code added for it.
Swapping in the generated form¶
Core's add-block route can point at the create operation's form. The plugin and theme in its path fix those keys, and the region and weight in its query start them, as core's form does today. _surface_form names the resource and the operation, the way _entity_form names an entity type and a form:
block.admin_add:
path: '/admin/structure/block/add/{plugin_id}/{theme}'
defaults:
- _controller: '\Drupal\block\Controller\BlockAddController::blockAddConfigureForm'
+ _surface_form: 'block.placement:create'
+ _surface_fixed: { plugin: '{plugin_id}', theme: '{theme}' }
+ _surface_query: { region: region, weight: weight }
theme: null
_title: 'Configure block'
requirements:
_permission: 'administer blocks'
+ plugin_id: '[^/]+'
+ theme: '[^/]+'
The two requirements bound the path values a route may put into the form. The proof of concept tests this swap on core's own route.
TBD
Core's edit and delete routes name the block {block}, and the operations take $id. A route cannot yet map a path variable onto an operation parameter of another name, so those two routes are not swapped. The edit route's _entity_access check would also need the route to load the block itself. The key names are the proof of concept's; core's are open.
What it gets¶
Every way in runs the same operation and the same checks. A region of another theme sent for a block in Stark is refused at /region: "The stark theme has no region named pre_content." Before it writes, the storage checks the whole block against core's block.block.* config schema, so what is stored is what core's block form would store.
Core's block form, its routes, every block plugin and their config schema stay as they are.