Create a simple Block programmatically

Submitted by editor on Mon, 01/18/2016 - 10:47
Question

How to create a simple block programmatically in drupal 8, Using drupal 8 plugins system.

In drupal 8 block is part of the plugin system.

Step 1. Create a simple module like this.

Step 2. Create a foldr Block in your module
Ex: mymodule\Plugin\Block

Step 3. Create the block (Php Class in mymodule\Plugin\Block )

<?php
/**
 * @file
 * Contains \Drupal\mymodule\Plugin\Block\MyBlock .
 */

namespace Drupal\mymodule\Plugin\Block;
use Drupal\Core\Block\BlockBase;

/**
 * Provides the  Block 'MyBlock'.
 *
 * @Block(
 *   id = "mymodule_myblock",
 *   subject = @Translation("MyBlock"),
 *   admin_label = @Translation("MyBlock")
 * )
 */
class MyBlock extends BlockBase {

  /**
   * Implements \Drupal\block\BlockBase::blockBuild().
   */
  public function build() {
    $output = array();
    //Add this two linew if you want to create a dynamic contents block
    $output['cache']['#disabled'] = TRUE;
    $output['cache']['max_age']['#value'] = 0;

    $html = "";
    $html .= 'This is a programmatically created block  :  ' . date("H:i:s") ;
    $output[] = [      '#markup' => $html,    ];
    return $output;
  }
}

Step 4. Add your block to a page

  • /admin/structure/block
  • Place a Block (Where you want to place the block)
  • Search your block 'MyBlock' and Place

Add new comment