“Learn to create a Drupal 9 custom module for a block with customizable text content using block settings.”
1. Module Creation:
Use Composer or Drush to create a new module:
composer create-project drupal/recommended-project my_moduleNavigate to the module directory:
cd my_module
2. Block Class:
- Create
src/Plugin/Block/CustomTextBlock.php:
<?php
namespace Drupal\my_module\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Provides a 'Custom Text Block' block.
*
* @Block(
* id = "custom_text_block",
* admin_label = @Translation("Custom Text Block"),
* )
*/
class CustomTextBlock extends BlockBase {
/**
* {@inheritdoc}
*/
public function build() {
$config = $this->getConfiguration();
$text = $config['text'] ?? '';
return [
'#type' => 'markup',
'#markup' => $text,
];
}
/**
* {@inheritdoc}
*/
public function blockForm($form, FormStateInterface $form_state) {
$form['text'] = [
'#type' => 'textarea',
'#title' => $this->t('Text'),
'#default_value' => $this->configuration['text'],
];
return $form;
}
/**
* {@inheritdoc}
*/
public function blockSubmit($form, FormStateInterface $form_state) {
$this->configuration['text'] = $form_state->getValue('text');
}
}
3. Module and Block Declaration:
- In
my_module.info.yml:
name: My Module
type: module
description: Provides a custom text block.
core: 8.x- In
my_module.libraries.yml:
custom_text_block:
version: 1.x
css:
theme:
css/custom_text_block.css: {}4. Clear Cache and Enable Module:
- Clear caches:
drush cr - Enable module:
drush en my_module
5. Place Block:
- Go to Structure > Block Layout > Custom Block Library.
- Find "Custom Text Block" and place it in a region.
- Configure the text in the block settings.
Additional Notes:
- Customize the CSS in
css/custom_text_block.css. - Add more settings to the block form as needed.
- Consider using a text filter for formatting the text.
- Validate and sanitize user input in the block configuration form.
