Drupal 8 Creating custom block from scratch

Drupal 8 Creating custom Block steps

Costume Module file structure (My Drupal version 8.1.2)

drupal 8 custom block structure

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

  1. ‘id’  = This property in the annotation defines the unique, machine readable ID of your block.

  2. ‘admin_label’  = This annotation defines the human readable name of the block that will be used when displaying your block in the admin interface.

drupal 8 block installation

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)

drupal 8 place block

8. Check the effect

drupal8block

 

Github : https://github.com/bikeshm/drupal-8-block-sample1

Check this post alos : https://wiki.workassis.com/drupal-8-creating-custom-module-from-scratch/

Author: bm on June 16, 2016
Category: Drupal 8