How to Create Configurable Block programmatically In Drupal 8
Blocks are the boxes of content that can be displayed in regions like sidebar first, sidebar second, content. This functionality is provided by the Block module in drupal 8. Here describing to creating Configurable Block programmatically in drupal 8 by using the drupal console.
Configurable Block module & skeleton files created by following drupal console commands:
$drupal generate: module
By using drupal console to generate configurable block module it create configure_block.info.yml file like,
Configure_block.info.yml file contain the following information:
The .info.yml file contains metadata about the project like the name of the project (configure_block), type (module), description (This is an example of configurable block programmatically in drupal 8), core (8.x), packages (Custom) and dependencies etc.
Next, we need to create a plugin for Block Module. Create folder Plugin under src, create Block folder under Plugin then create DefaultBlock.php file under Block folder.
- The path should be /src/Plugin/Block/DefaultBlock.php
Next, we need to generate Block module using following drupal console command,
After generated configurable block module by using drupal console, it should be like,
The Configurable block module Skeleton in drupal 8 is like this:
where configure_block is a module name for our custom configurable block. The plugin of configurable block module file will have following code where we are defining our configurable fields in drupal 8.
Here we take three fields of the configurable block which are hello_block_name, mobile_number and address. The message is to be displayed, based on what you enter in those fields of block module in drupal 8.
Next, install your configurable block module in drupal 8.
Extend >select install module>select your module name>click install.
Next place the configurable Block module in any regions are presented in drupal 8.
Structure>Block Layout>click place block icon>select your block name>select region>save block.
Configuration block>enter in the following field what you need to display output.
Then go to the main page,
Configurable block Module displayed in some region (selected region example: sidebar second). It shows following output.
I hope this was helpful in getting you started with Custom configurable block in Drupal 8.