8

I want to create a static block using a module. I do not want to use the Views module to create a block. Could anyone explain me how to create a static block programmatically?

I have already checked the example modules in Drupal, but it didn't help me much. I have started Drupal module development every recently and I am struggling to do this.

21

The important hooks in the Block example module are hook_block_info() and hook_block_view(). The info hook defines your block in the system and the view hook creates the output (html) for your block.

Every module, including yours, will have at least a .info file and a .module file. Drupal.org has some more documentation about .info files that you may find helpful when getting started with modules. Yours really just needs the name and core entries.

The .module file is where you'll implement your hooks. First, implement hook_block_info(), replacing 'hook' in the function name with the name of your module, e.g., my_module_block_info(). It should look something like the following.

function my_module_block_info() {    
  $blocks['your_block'] = array(
    // info: The name of the block.
    'info' => t('Your Block Name'),
  );

  return $blocks;
}

Then, implement your hook_block_view() hook to define the static content.

function my_module_block_view($delta = '') {
  // The $delta parameter tells us which block is being requested.
  switch ($delta) {
    case 'your_block':
      // Create your block content here
      $block['subject'] = t('Title of first block (example_configurable_text)');
      $block['content'] = 'Your block content, or the result of a function that returns the content';
      break;
  }

  return $block;
}

Once you have that in place, you can put your block in any region as you would any other block in Drupal.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy