Drupal 8 Module Port - Blocks and the Plugin API

This is Part 4 of a blog series about my recent experiences of porting the Instagram Block module from Drupal 7 to Drupal 8. Since Drupal 8 is still in alpha, APIs are subject to change. Also I may not be using best practises so commenting is heavily appreciated!

This time we are going to dig deep into Drupal 8, and have a look at the new Plugin API. With ctools in core it was about time to re-examine blocks for Drupal 8. Blocks are now Plugins (as are views, entities and virtually everything else..), but what does that mean practically?

We no longer use hook_block_info, hook_block_view, hook_block_allthethings, etc. to store blocks in code, we simply extend the BlockBase class in:

'lib/Drupal/MYMODULE/Plugin/Block/CLASSNAME.php'.

(If this seems weird, see the previous post about forms)

Show me code!

This is what my class in InstagramBlockBlock.php looks like:

This looks a bit daunting at first, but all you really need is build() to build the render array and (VERY IMPORTANT) the plugin definition in the class docblock.

Important Notes

"What I put in the comment matters?!", I hear you asking... Yes it does! In Drupal 8 we implement Doctrine's Annotation system which means most classes need to have Annotations to register the plugins they are defining. In other words, if your class commenting is wrong, your block will not be found by Drupal.

For our block we need the id and admin_label.

And boom, we have a block!

Now of course we don't just want a block that is hardcoded, we want a configurable block. So we need to implement blockForm() and blockSubmit(), which allow us to put a form on the block edit page without having to use hook_block_configure() and hook_block_save().

Once you have defined your block in code, you can go to admin/structure/block page and 'place' the block in the theme using the UI on the right side of that page.