Drupal 8 allows creating custom block with the help of oops concepts. Each block in drupal 8 should be defined in a separate plugin file. Before starting developing a custom block you should have a basic knowledge about a custom module. Please have a look at my previous post, create a custom module in drupal 8 to get an idea about custom modules.
Create a Block plugin file
Block plugin file is a class and placed inside our custom module directory in the path src/Plugin/Block. In this tutorial we are going add the plugin file inside our custom module simple_module. Create a new folder src/Plugin/Block inside our custom module and create a new file MyCustomBlock.php inside it.
This file basically contains two parts,
1. Annotation metadata, uses to tell drupal about the block
2. The MyCustomBlock class
Now, lets create our first custom block file,
MyCustomBlock.php
<?php namespace Drupal\simple_module\Plugin\Block; use Drupal\Core\Access\AccessResult; use Drupal\Core\Block\BlockBase; use Drupal\Core\Session\AccountInterface; /** * Provides a Custom Block. * * @Block( * id = "my_custom_block", * admin_label = @Translation("My Custom Block"), * category = @Translation("Custom Blocks"), * ) */ class MyCustomBlock extends BlockBase { /** * {@inheritdoc} */ public function build() { return array(, '#markup' => 'My custom block will be displayed here' ); } /** * {@inheritdoc} */ protected function blockAccess(AccountInterface $account) { return AccessResult::allowedIfHasPermission($account, 'access content'); } }
Clear drupal cache and your custom block will be available to use.
That's all for creating a custom block in drupal 8. Please comment your questions and suggestions below or put it in a mail to me@praveenpb.com
Add new comment