How to create custom block in Drupal 8 programmatically

0
(0)

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 itblog_block.info.yml file under the modules/custom/itblog_block folder. Inside this file enter following:

name: Itblog Block
description: Create a custom block module
package: webdigg
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

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

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

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

    return [
        '#markup' => "<span>$itblog_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 ItBlog. All Rights Reserved.', [
        '@year' => $current_year
    ]);

    $form['itblog_copyright'] = [
        '#type' => 'textfield',
        '#title' => $this->t('Copyright'),
        '#description' => $this->t('Write your copyright text.'),
        '#default_value' => isset($config['itblog_copyright']) ? $config['itblog_copyright'] : $itblog_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('itblog_copyright', $form_state->getValue('itblog_copyright'));
}

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

/**
 * {@inheritdoc}
 */
public function blockValidate($form, FormStateInterface $form_state)
{
    if (empty($form_state->getValue('itblog_copyright'))) {
        $form_state->setErrorByName('itblog_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\itblog_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 'Itblog Block' Block.
 *
 * @Block(
 *   id = "itblog_block",
 *   admin_label = @Translation("Itblog block"),
 *   category = @Translation("Itblog"),
 * )
 */
class ItblogBlock extends BlockBase implements BlockPluginInterface
{
    /**
     * {@inheritdoc}
     */
    public function build()
    {
        $config = $this->getConfiguration();
        $codimth_copyright = $config['itblog_copyright'];

        return [
            '#markup' => "<span>$itblog_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 ItBlog. 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['itblog_copyright']) ? $config['itblog_copyright'] : $itblog_copyright,
        ];

        return $form;
    }

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


    /**
     * {@inheritdoc}
     */
    public function blockValidate($form, FormStateInterface $form_state)
    {
        if (empty($form_state->getValue('itblog_copyright'))) {
            $form_state->setErrorByName('itblog_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.

Similar Posts:

847

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Summary
Scroll to Top