Create a simple Block programmatically | Drupal 8

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

 

See also to add a block programatically

$block_manager = \Drupal::service('plugin.manager.block');
$config = [];// You can hard code configuration or you load from settings.
$plugin_block = $block_manager->createInstance('system_breadcrumb_block', $config);
// If want to access check.
$access_result = $plugin_block->access(\Drupal::currentUser());
if (is_object($access_result) && $access_result->isForbidden() || is_bool($access_result) && !$access_result) {
  return [];
}
$render = $plugin_block->build();
// Add the cache tags/contexts.
\Drupal::service('renderer')->addCacheableDependency($render, $plugin_block);
return $render;

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.