How to create a block with Drush in Drupal (9, 10, 11)

To create a block, you can use the drush generate (shortcut: drush gen) command. Here is a full output of bash script, where I create a search bar block with drush:

bash$ drush gen plugin:block

 Welcome to block generator!
–––––––––––––––––––––––––––––

 Module machine name [web]:
 ➤ test

 Block admin label [Example]:
 ➤ SearchBar

 Plugin ID [mymodule_searchbar]:
 ➤

 Block category [Custom]:
 ➤ Custom

 Make the block configurable? [No]:
 ➤

 Would you like to inject dependencies? [No]:
 ➤

 Create access callback? [No]:
 ➤

 The following directories and files have been created or updated:
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––
 • /var/www/html/web/modules/custom/mymodule/src/Plugin/Block/SearchbarBlock.php

This has created a base file SearchBarBlock.php with a default block plugin code:

<?php

namespace Drupal\my_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'My Custom Block' Block.
 *
 * @Block(
 *   id = "searchbar",
 *   admin_label = @Translation("My custom block"),
 *   category = @Translation("Custom"),
 * )
 */
class SearchBarBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    return [
      '#markup' => $this->t('Content of my custom block.'),
    ];
  }

}

 

 

Saved you some valuable time?

Buy me a drink 🍺 to keep me motivated to create free content like this!