Skip to main content
Category:

Blocks, are pieces of content that can be placed anywhere on your Drupal site. in this tutorial I’ll show you how to write a simple Drupal 8 module that will display output in a block. when you’re done you will have created a new block that you can place in one or more regions.

Create a module

In Drupal 8, it is necessary to create an info.yml file that contains the metadata for every custom module. you will need to create the codimth_block.info.yml file under the modules/custom/codimth_block folder. Inside this file enter following:

name: CodimTh Block
description: Create a custom block module
package: CodimTh
type: module
core: 8.x
dependencies:
  - block

Once the folder and file has been created, you can go to your Drupal dashboard and enable the custom module we have just created.

Create a Block Class

Now, we’ll create a class that will contain the logic of our block. we’ll place our CodimthBlock.php class under the modules/custom/codimth_block/src/Plugin/Block directory. 
The class file should contain annotation as well. The annotation allows us to identify the bloc, also this class will contain 6 methods:

build(): required method which is expected to return a render array defining the content you want your block to display.

/**
 * {@inheritdoc}
 */
public function build()
{
    $config = $this->getConfiguration();
    $codimth_copyright = $config['codimth_copyright'];

    return [
        '#markup' => "<span>$codimth_copyright</span>",
    ];
}

 

blockForm(): This method allows you to define a block configuration form using the Form API.

/**
 * {@inheritdoc}
 */
public function blockForm($form, FormStateInterface $form_state)
{
    $form = parent::blockForm($form, $form_state);

    $config = $this->getConfiguration();

    $current_year = date("Y");
    $codimth_copyright = $this->t('©@year codimTh. All Rights Reserved.', [
        '@year' => $current_year
    ]);

    $form['codimth_copyright'] = [
        '#type' => 'textfield',
        '#title' => $this->t('Copyright'),
        '#description' => $this->t('Write your copyright text.'),
        '#default_value' => isset($config['codimth_copyright']) ? $config['codimth_copyright'] : $codimth_copyright,
    ];

    return $form;
}

 

blockSubmit(): This method used to save a configuration, defined on the blockForm() method.

/**
 * {@inheritdoc}
 */
public function blockSubmit($form, FormStateInterface $form_state)
{
    parent::blockSubmit($form, $form_state);
    $this->setConfigurationValue('codimth_copyright', $form_state->getValue('codimth_copyright'));
}

 

blockValidate(): This method used to validate block configuration form.

/**
 * {@inheritdoc}
 */
public function blockValidate($form, FormStateInterface $form_state)
{
    if (empty($form_state->getValue('codimth_copyright'))) {
        $form_state->setErrorByName('codimth_copyright', t('This field is required'));
    }
}

 

getCacheMaxAge(): This method used if you want to change block cache max time.

/**
 * {@inheritdoc}
 * return 0 If you want to disable caching for this block.
 */
public function getCacheMaxAge()
{

    return 0;
}

 

access(): Defines a custom user access logic. It is expected to return an AccessResult object.

/**
 * {@inheritdoc}
 */
public function access(AccountInterface $account, $return_as_object = FALSE)
{
    return AccessResult::allowedIfHasPermission($account, 'access content');
}

 

Now, this is what the class file should contain in the end:

<?php

namespace Drupal\codimth_block\Plugin\Block;

use Drupal\Core\Access\AccessResult;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;

/**
 * Provides a 'Codimth Block' Block.
 *
 * @Block(
 *   id = "codimth_block",
 *   admin_label = @Translation("Codimth block"),
 *   category = @Translation("Codimth"),
 * )
 */
class CodimthBlock extends BlockBase implements BlockPluginInterface
{
    /**
     * {@inheritdoc}
     */
    public function build()
    {
        $config = $this->getConfiguration();
        $codimth_copyright = $config['codimth_copyright'];

        return [
            '#markup' => "<span>$codimth_copyright</span>",
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function blockForm($form, FormStateInterface $form_state)
    {
        $form = parent::blockForm($form, $form_state);

        $config = $this->getConfiguration();

        $current_year = date("Y");
        $codimth_copyright = $this->t('©@year codimTh. All Rights Reserved.', [
            '@year' => $current_year
        ]);

        $form['codimth_copyright'] = [
            '#type' => 'textfield',
            '#title' => $this->t('Copyright'),
            '#description' => $this->t('Write your copyright text.'),
            '#default_value' => isset($config['codimth_copyright']) ? $config['codimth_copyright'] : $codimth_copyright,
        ];

        return $form;
    }

    /**
     * {@inheritdoc}
     */
    public function blockSubmit($form, FormStateInterface $form_state)
    {
        parent::blockSubmit($form, $form_state);
        $this->setConfigurationValue('codimth_copyright', $form_state->getValue('codimth_copyright'));
    }


    /**
     * {@inheritdoc}
     */
    public function blockValidate($form, FormStateInterface $form_state)
    {
        if (empty($form_state->getValue('codimth_copyright'))) {
            $form_state->setErrorByName('codimth_copyright', t('This field is required'));
        }
    }

    /**
     * {@inheritdoc}
     * return 0 If you want to disable caching for this block.
     */
    public function getCacheMaxAge()
    {

        return 0;
    }

    /**
     * {@inheritdoc}
     */
    public function access(AccountInterface $account, $return_as_object = FALSE)
    {
        return AccessResult::allowedIfHasPermission($account, 'access content');
    }

}

 

Next steps

  • Clear your Drupal 8 caches. To do this I use this Drush command: drush cr if you don’t currently use Drush, I highly recommend using it, or the Drupal Console.
  • Now, go back to your site, and you should be able to see the block you have just created. Simply place the block to a region and it should become visible.
  • I hope you found this article useful. let me know if you have any questions and I’ll be happy to answer them.
  • This code can be found and downloaded from https://github.com/codimth/codimth_block.

 

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.