Drupal 8 Creating custom Block steps
Costume Module file structure (My Drupal version 8.1.2)
1. Create a folder under ‘/modules/’ for this explanation I am creating a ‘sampleblk’ (this is our module folder) folder inside module folder
2. Create module info file ‘sampleblk.info.yml’ inside sampleblk folder
name: Sample Block type: module description: 'Example Block for Drupal 8.' package: Custom version: 8.x core: 8.x dependencies: - node - block
3. Create sampleblk.module inside sampleblk folder
<?php /** * @file */ ?>
4. Create src folder and create Plugin folder inside ‘src’ and create Block folder inside ‘src\Plugin\’ folder and create SampleblkBlock.php filde (full path : modules\sampleblk\src\Plugin\Block\SampleblkBlock.php)
<?php /** * @file */ namespace Drupal\sampleblk\Plugin\Block; use Drupal\Core\Block\BlockBase; /** * Provides a 'Hello' Block * @Block( * id = "sample_block", * admin_label = @Translation("Sample block"), * ) */ class SampleblkBlock extends BlockBase { /** * * {@inheritdoc} * */ public function build() { return array ( '#type' => 'markup', '#markup' => 'This is sample Block content.', ); } } ?>
Here in the comment section adding some annotation @block don’t remove it it is required. Read more about annotation
-
‘id’ = This property in the annotation defines the unique, machine readable ID of your block.
-
‘admin_label’ = This annotation defines the human readable name of the block that will be used when displaying your block in the admin interface.
5. Install the new module from admin
6. clear the cache
7. Add your new block (I am just adding the new block to sidebar)
8. Check the effect
Github : https://github.com/bikeshm/drupal-8-block-sample1
Check this post alos : https://wiki.workassis.com/drupal-8-creating-custom-module-from-scratch/