Creating a custom module in Drupal 8 The undying "Hello World!"

Submitted by galactus on Sun, 02/24/2019 - 02:17

In this tutorial I'm going to show you a step by step guide on how to create a custom module in Drupal 8 from the scratch. We are going create a custom block that display the undying "Hello World" message.

Let's get started

  1. Inside your module folder(hello_world) create

  2. Let's make Drupal aware that our module is existing, tell something about hello_world module, copy this code and paste it on your file.

    name: Hello World
    description: Awesome module that display blocks and page
    package: Custom
    type: module
    core: 8.x


  3. Navigate to admin/modules and enable hello_world module.helloworldenable

  4. Create HelloWorldBlock.php under src/Plugin/Block.HelloWordBlock

  5. Tell something about your block to display "Hello World". Copy and paste this code snippet under your HelloWorldBlock.php file.

    namespace Drupal\hello_world\Plugin\Block;
    use Drupal\Core\Block\BlockBase;
     * Provides a 'Hello World' Block.
     * @Block(
     *   id = "hello_block",
     *   admin_label = @Translation("Hello World block"),
     *   category = @Translation("Hello World"),
     * )
    class HelloWorldBlock extends BlockBase {
       * {@inheritdoc}
      public function build() {
        return array(
          '#markup' => $this->t('Hello, World!'),
  6. Enable your hello world block under admin/structure/block home page.enable_block

  7. Visit your home page.


Voila you now have your first Drupal 8 custom module.