Create custom block using code in Drupal 8

author details
AdiPie
25th Jul 2020
3 mins read
Image
custom block in drupal

Create a module

First we make an folder under "/modules/custom" (you should make the 'custom' folder), called "my_block_test".

Inside custom folder make "info.yml" file

my_block_test.info.yml

name: My Block

Example type: module

description: Defines a custom block.

core: 8.x package: WebWash

dependencies: - block

When the folder and file has been made, enable the module. Kindly note, Drupal 8 doesn't require a ".module".

Create a Block Class

In this progression, we will make a block class that will contain the rationale of our block. We will put our PHP class under /modules/custom/my_block_test/src/Plugin/Block. Make this envelope structure and afterward make another document called MyBlock.php under it.

The way to the block class should wind up being my_block_test/src/Plugin/Block/MyBlock.php. 

The MyBlock class, containing 4 techniques:

build(), blockAccess(), blockForm(), and blockSubmit()

So, let’s create it

<?php

namespace Drupal\my_block_test\Plugin\Block;

use Drupal\Core\Access\AccessResult;

use Drupal\Core\Block\BlockBase;

use Drupal\Core\Form\FormStateInterface;

use Drupal\Core\Session\AccountInterface;

/**

* Provides a block with a simple text.  

* @Block( * id = "my_block_test",

* admin_label = @Translation("My block"),

* )

*/

class MyBlock extends BlockBase {

/**

* {@inheritdoc}

*/

public function build() {

     return [

         '#markup' => $this->t('This is a simple block!'),

    ];

}

}

That is it! Your block is made and fit to be utilized! Simply appoint the block to an region and you should see it.

build()

This strategy will render a renderable array. For our situation, we're restoring a fundamental markup however we could have restored a progressively intricate code, similar to a form or a view. 

The code underneath shows how to render a structure for instance:

/**

*  { @inheritdoc }

*/

public function build() {

    return \Drupal::formBuilder()->getForm('Drupal\my_module\Form\MyBlockForm');

}