cmcintosh's picture

Creating Custom blocks in Drupal 8 are a little different these days thanks to the change to the new Symfony api.  This means that most things you used to do as procedural functions are now created via the Plugin API, Entity API, or other Object Oriented methods.  So for Custom blocks we are creating a instance of the Block plugin, that will provide the functionality and content we are looking to create with the new Drupal 8 custom block. Below you can see a small bit of the code for a custom block, we will go over each section one step at a time.

The first step in creating your new custom Block's class is to define it via the Annotation API system.  This new method of telling Drupal about elements in your modules will make adding components to existing custom modules a bit easier once you get the basics down.

A Simple Block

Above you can see that the @Block annotation contains a id, admin_label, and category property.  These are all required in order for your custom block to properly display on the Block Administration page or in Contexts. Another thing to keep in mind that caused me to scratch my head at first is to make sure to use double-quotes(") instead of single quotes as this can cause issues and errors where there may not be.

You will want to make sure that you place the new php file in your custom module's src/Plugin/Block directory.  This is pretty standard for any of the new Plugin API plugins that you use. Next steps for this first example would be to create a theme function for it so that you can control the templating and look of the output.  Pretty much all output is not handled by modules via Render Arrays, which can make things hard to follow at first, but you should start picking things up quickly after your first couple of modules.

Displaying a Form API From in a Block

The next step when it comes to creating custom blocks is often creating a form for user input, and then placing it in the layout of the page.  So I would like to go over the simple changes needed to accomplish that.  You will need to first create your Drupal 8 Form API form, see this the Drupal 8 Form API tutorial if you need help. Then once you have your form finished, you can follow the code below

As you can see above we are getting the form using the new Drupal 8 Form builder service, one of the many new Drupal 8 Services available, to get the renderable array to display the form.  We then just pass this as a part of the return for the build function of our block.

Planned Topic: 

Add new comment