Create a block programatically in Drupal 8

​​block_example.PNG

Basic creation of a block in Drupal 8. As seen in the image on the left, a predefined library structure is needed to create a block plugin.

The annotations plugin is used to handle the block id, subject and admin label from within the comment block. The annotation class is found at core/lib/Drupal/Component/Annotation/Plugin.php.

block_example.info.yml


name: Block example
type: module
description: 'Create blocks.'
package: Dribbit examples
core: 8.x
dependencies:
  - block

block_example.module


/**
 * @file
 * Currently (31/01/2014) , Drupal needs this blank file.
 */

BlockExampleSimpleBlock.php


/**
 * @file
 * Contains \Drupal\block_example\Plugin\Block\BlockExampleSimpleBlock.
 */

namespace Drupal\block_example\Plugin\Block;

use Drupal\block\BlockBase;
use Drupal\Component\Annotation\Plugin;
use Drupal\Core\Annotation\Translation;

/**
 * Provides a 'Example: empty block' block.
 *
 * @Block(
 *   id = "example_simple",
 *   subject = @Translation("Simple example block"),
 *   admin_label = @Translation("Simple example block")
 * )
 */
class BlockExampleSimpleBlock extends BlockBase {
  
  /**
   * Implements \Drupal\block\BlockBase::blockBuild().
   */
  public function build() {
    return array(
      '#markup' => t('Simple example block data'),
    );
  }

}

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.