Skip to main content
Drupal 8

Main navigation

  • Home
    • Question And Answer
    • NEWS
    • Projects
  • Tutorials - Drupal
    • Android
    • Other
User account menu
  • Log in

Breadcrumb

  1. Home

Create a simple Block programmatically

By editor , 18 January, 2016
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;

Tags

  • Drupal 8
  • Code
  • Module
  • Plugin
Create a simple module for Drupal 8 - Step 1
Drupal 8 Plugin API

Comments

Plain text

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

Links

  • Drupal.org
  • Drupal core release cycle
  • Drupal events with ease
  • Unit test with Drupal using PHPUnit (Drupal 10)
  • Tokens for file upload url
  • Tips for Docker
  • CKEditor inline image files usage for custom forms.
  • Install Docker on Linux Mint
  • Install PHP 8.1
  • Drupal Security Best Practices
  • Order and sort items with tabledrag
  • Add a custom service YAML container
  • Apply a patch with composer