Drupal code a block with an edit form

Sometimes you need to code a block with an edit form. You could just create a block with the UI but that's not going to be exportable with Features and ctools / page manager. This method uses variable_get and variable_set. You may want to create a custom db table to store the data in if you don't want the variables to be loaded into memory on every page load.

<?php
 
/**
 * @file
 * mymodule.module 
 */
define('MY_BLOCK_NAME', 'myblock');
define('MY_BLOCK_CONTENT', 'myblock_content');
 
/**
 * Implementation of hook_block_info
 */
function mymodule_block_info() {
  $blocks[MY_BLOCK_NAME] = array(
    'info' => t('My Block'),
    'cache' => DRUPAL_CACHE_GLOBAL,
  );
  return $blocks;
}
 
/**
 * Implementation of hook_block_configure
 */
function mymodule_block_configure($delta) {
  switch ($delta) {
    case MY_BLOCK_NAME:
      $form['content'] = array(
        '#type' => 'text_format',
        '#title' => t('Content'),
        '#default_value' => variable_get(MY_BLOCK_CONTENT, ''),
      );
 
      return $form;
      break;
  }
}
 
/**
 * Implementation of hook_block_save
 */
function mymodule_block_save($delta = '', $edit = array()) {
  switch ($delta) {
    case MY_BLOCK_NAME:
      variable_set(MY_BLOCK_CONTENT, trim($edit['content']['value']));
      break;
  }
}
 
/**
 * Implementation of hook_block_view
 */
function mymodule_block_view($delta) {
  $block = array();
  switch ($delta) {
    case MY_BLOCK_NAME:
      $block['subject'] = '<none>';
      $block['content'] = array(
        'message' => array(
          '#type' => 'markup',
          '#markup' => variable_get(MY_BLOCK_CONTENT, ''),
        )
      );
      break;
  }
  return $block;
}
?>

Tags

Internal References

Article Type

General