Drupal 7 - Creating block programmatically

Drupal blocks are the reusable content holder that can be placed anywhere in the region of the page. You can manage them and their configuration from the Structure area of the Drupal back-end. Each theme defines certain sections in their page where you can assign the block to them. 

Although, Drupal developer can use the Drupal admin area to manage and create the block, but there is another way to create them as well. You can create the block by doing the coding yourself. This feature of drupal allows you to add the display component to website bases on your programming logic.

To create the custom block by programmng, follow the following steps.

 

Step 1: Create the module

create the folder example at /sites/all/module path. and create the example.info file which is used by drupal to understand more about your module.

name = Example
description = Module for creating custom block
core = 7.x
files[] = example.module

Step 2: Create the example.module file. This file is read by drupal and hook functions are executed wherever needed by drupal on difrrent event. So, you need to write your code in the hook functions so that drupal can get them executed.

<?php
/**
 * Implements hook_block_info().
 */
function example_block_info() {

  $blocks['example_block'] = array(
    'info' => t('Example Block'),
    'description'=>t('This is custom block'),
    'cache' => DRUPAL_NO_CACHE // this will exclude the block from Drupal cache
  );

  return $blocks;
}

/**
 * This hook generates the contents of the blocks.
 */
function example_block_view($delta = '') {

  switch ($delta) {
    case 'olive_block':
      $block['subject'] = 'Hello';
      $block['content'] = '<h1>This is My Block</h1>';
  }
  return $block;
}

Step 3: Go in the Drupal admin and assign this block to a region. 

Creating drupal block programmatically

 

And you will see the following output.

 

Creating drupal block programmatically result

Tags

Comments

Submitted by Darlene Culver (not verified) on Wed, 02/22/2023 - 23:35

Permalink

Comment

To the greaterthan0.com admin, Your posts are always a great source of knowledge.