In the first installment of this article series on Drupal 8 module development we started with the basics. We’ve seen what files were needed to let Drupal know about our module, how the routing process works and how to create menu links programatically as configuration.
In this tutorial we are going to go a bit further with our sandbox module found in this repository and look at two new important pieces of functionality: blocks and forms. To this end, we will create a custom block that returns some configurable text. After that, we will create a simple form used to print out user submitted values to the screen.
Drupal 8 blocks
A cool new change to the block API in D8 has been a switch to making blocks more prominent, by making them plugins (a brand new concept). What this means is that they are reusable pieces of functionality (under the hood) as you can now create a block in the UI and reuse it across the site - you are no longer limited to using a block only one time.
Let’s go ahead and create a simple block type that prints to the screen Hello World! by default. All we need to work with is one class file located in the src/Plugin/Block
folder of our module’s root directory. Let’s call our new block type DemoBlock
, and naturally it needs to reside in a file called DemoBlock.php
. Inside this file, we can start with the following:
<?php
namespace Drupal\demo\Plugin\Block;
use Drupal\block\BlockBase;
use Drupal\Core\Session\AccountInterface;
/**
* Provides a 'Demo' block.
*
* @Block(
* id = "demo_block",
* admin_label = @Translation("Demo block"),
* )
*/
class DemoBlock extends BlockBase {
/**
* {@inheritdoc}
*/
public function build() {
return array(
'#markup' => $this->t('Hello World!'),
);
}
/**
* {@inheritdoc}
*/
public function access(AccountInterface $account) {
return $account->hasPermission('access content');
}
}
Like with all other class files we start by namespacing our class. Then we use the BlockBase
class so that we can extend it, as well as the AccountInterface
class so that we can get access to the currently logged in user. Then follows something you definitely have not seen in Drupal 7: annotations.
Continue reading %Building a Drupal 8 Module: Blocks and Forms%
more
{ 0 comments... » Building a Drupal 8 Module: Blocks and Forms read them below or add one }
Post a Comment