With over a decade of web development experience, I specialize in Drupal (7, 8, 9, 10), CodeIgniter, Laravel, and WordPress. I offer extensive expertise in both module and theme development, providing customized solutions for complex projects. Whether you need to enhance an existing platform, create new features, or seek expert guidance, I'm here to assist. My dedication to delivering high-quality, efficient, and scalable solutions is unmatched. Feel free to contact me to explore how I can contribute to your project's success. Let's turn your ideas into reality!

“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_module

  • Navigate 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.
Posted by Sujan Shrestha
Categorized:
PREVIOUS POST
banner