Programmatically create a custom block in Drupal 8

  1. It seems that we cannot create a custom block in existing modules on drupal 8. So you must create a new custom module first.
    • create a .info.yml file like so: /modules/custom_blocks/
      name: All My Custom Blocks
      type: module
      description: Defines a custom block.
      core: 8.x
      package: Custom
        - block
  2. Create the following file /modules/custom_blocks/src/Plugin/Block/MyFirstBlock.php
    • Please note that some comments may useful for the drupal 8. To avoid unexpected error occur you must copy them carefully. 
      namespace Drupal\custom_blocks\Plugin\Block;
      use Drupal\Core\Block\BlockBase;
       * Provides a 'Example: empty block' block.
       * @Block(
       *   id = "my_first_block",
       *   admin_label = @Translation("My First Block")
       * )
      class MyFirstBlock extends BlockBase {
         * {@inheritdoc}
         * The return value of the build() method is a renderable array. Returning an
         * empty array will result in empty block contents. The front end will not
         * display empty blocks.
         public function build() {
          // We return an empty array on purpose. The block will thus not be rendered
          // on the site. See BlockExampleTest::testBlockExampleBasic().
          return [
            '#markup' => $this->t('This is a simple block!'),
  3. Enable "All My Custom Blocks" module 
  4. Visit /admin/structure/block 
  5. You can found the "My First Block" module by click on “place block” under one of the region.