I am learning Drupal 8, i know how to create block programmatically in Drupal 7.
Can anyone please suggest how can u create block and render that block in more than one region in Drupal 8?
The 'id' property in the annotation defines the unique, machine readable ID of your block.
The 'admin_label
' annotation defines the human readable name of the
block that will be used when displaying your block in the admin
interface.
The 'Category' defines which section belongs to under block listing page.
The Drupal block manager scans your module's classes for a class that contains the @Block Annotation (a special comment right above your class declaration)
<?php
/**
* @file
* Contains \Drupal\article\Plugin\Block\XaiBlock.
*/
namespace Drupal\article\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
* Provides a 'Article' Block
* @Block(
* id = "article_block",
* admin_label = @Translation("Article block"),
* )
*/
class ArticleBlock extends BlockBase {
/**
* {@inheritdoc}
*/
public function build() {
return array(
'#type' => 'markup',
'#markup' => 'This block list the article.',
);
}
Creating a custom block require following steps:
Create a block plugin using Annotations Extend the Drupal\Core\Block\BlockBase class. In Drupal 8, We need to keep the keep our custom, contributed module in root directory
modules/custom
module/contrib
Step 1: An essential part of a Drupal 8 module, theme, or install profile is the .info.yml file (aka, "info yaml file") to store metadata about the project.
In Drupal 8, .info file changes to .info.yml. Old .info files have been converted to YAML.
Added name, description, core, package, dependencies, type (The type key, which is new in Drupal 8, is required and indicates the type of extension, e.g. module, theme or profile.
Step 2: We should follow the PSR-4 standard code for custom block(s) & that has to be placed into article/src/Plugin/Block/ and named based on the class it contains. If we're going to define the class ArticleBlock this file would be article/src/Plugin/Block/ArticleBlock.php
Create a file ArticleBlock.php under modules/custom/article/src/Plugin/Block folder structure
Annotation contains just the id and label:
The 'id' property in the annotation defines the unique, machine readable ID of your block. The 'admin_label' annotation defines the human readable name of the block that will be used when displaying your block in the admin interface. The 'Category' defines which section belongs to under block listing page.
The ArticleBlock extends BlockBase class. This class provides generic block configuration form, block settings and handling of user defined block visibility settings.
Save the file and enable the module. To enable a block visit /admin/structure/block and click on “place block” under one of the region. i’m selecting “Sidebar Second” for my visibility or search for your block “Article block” click on “place block” and configure it.
I hope this helps.. :)