Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
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.

 

Comments

Submitted by Omar (not verified) on Fri, 04/09/2021 - 07:52 Permalink

Thanks for your tutorial. i have a small question in this way block is created and by manually we can assign to any region from structure > block layout but can we do this also via programming how please guide me how we can assign block to region automatically soon after we created the block from custom module
Submitted by Omar (not verified) on Fri, 04/09/2021 - 11:31 Permalink

I created a block with this above method. Now i have to go to structure then block layout then i have to choose the block and assign to region and select the page for visibility. Now here my question is what code i have to write for over come these manual changes. I want to add additional code in same module so my newly created block start appearing on home page content region. please guide me solution
Add new comment

Restricted HTML

If you need some help or you search a Drupal freelancer don't hesitate to contact us.

 

Contact Us

All the content is FREE but I still need your help

 

Become a patreon