Drupal8 : How to create a “custom block ” programatically

499

Drupal 8 : Create custom block in drupal 8, follow given below steps to create custom block programatically .

before starting creation of “custom block “, we need to know about Plugin API overview & Annotations-based plugins .

Related article: how to create custom module in drupal 8

Most Important  part of a Drupal 8 module, theme, or install profile is the .info.yml file to store metadata about the project.

  •  Create new folder in module’s src folder called Plugin. which is store all Plugin of this module.  common>>src>>Plugin
  • Create Block folder in Plugin folder.  A Block is a Plugin Type
  • common>>src>>Plugin>>Block
  • And Inside the Block folder create file like: “MyBlock.php”

 Custom Block folder structure:

Drupal8 : How to create a "custom block " programatically
Custom Module Structure

Custom Block file

In that file (MyBlock.php). Add Namespace and Use use Drupal\Core\Block\BlockBase;

<?php
/**
 * @file
 * Contains \Drupal\common\Plugin\Block\MyBlock.
 */
namespace Drupal\common\Plugin\Block;
use Drupal\Core\Block\BlockBase;

 

 

Add Class and Extends Base Class :

<?php
/**
 * @file
 * Contains \Drupal\common\Plugin\Block\MyBlock.
 */
namespace Drupal\common\Plugin\Block;
use Drupal\Core\Block\BlockBase;

class MyBlock extends BlockBase {

}

You need to add code Comment in specific way. called an Annotation. Above class MyBlock extends BlockBase :


<?php

/**
* Provides a 'myblock' block.
*
* @Block(
* id = "myblock_block",
* admin_label = @Translation("My Block"),
* category = @Translation("Custom my block example")
* )
*/

class MyBlock extends BlockBase {
/**
* {@inheritdoc}
*/

The All Code for MyBlock.php .

<?php
 /**
 * @file
 * Contains \Drupal\common\Plugin\Block\MyBlock.
 */
 namespace Drupal\common\Plugin\Block;
 use Drupal\Core\Block\BlockBase;
 /**
 * Provides a 'myblock' block.
 *
 * @Block(
 * id = "myblock_block",
 * admin_label = @Translation("My Block"),
 * category = @Translation("Custom my block example")
 * )
 */

class MyBlock extends BlockBase {
 /**
 * {@inheritdoc}
 */
 public function build() {
 return array(
 '#type' ='markup',
 '#markup' ='This block list My Block.',
 );
 }
 }

Go >> admin/structure/block and search your block.

Drupal8 : How to create a "custom block " programatically

Configure Block. you can configure Language, Content types, Pages Roles

Drupal8 : How to create a "custom block " programatically

Click Save block and  visit our page.

Drupal8 : How to create a "custom block " programatically

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here