2

To create a block I am currently using this code:

$default_theme = variable_get('theme_default', getDefaultTheme());
$blocks = array(
  array(
    'module' => 'user',
    'delta' => 'login',
    'theme' => $default_theme,
    'status' => 1,
    'weight' => 0,
    'region' => 'sidebar_first',
    'pages' => '',
    'cache' => -1,
    ),
);

// Save blocks
$query = db_insert('block')->fields(array('module', 'delta', 'theme', 'status', 'weight', 'region', 'pages', 'cache'));
foreach ($blocks as $block) {
  $query->values($block);
}
$query->execute();

My question is what do the 'module' and 'delta' field exactly do? What can I fill in there if I made a custom block? And how do I define on which pages this block should be visible, should I add a page name or id?

0

I think that's not the correct way of creating the block as it won't fire the required api call for block creation and later on will cause issue.

Delta: This is a unique identifier for the block within the module. Delta values only need to be unique and is used in following purposes:

  • Passed into the other block hooks in your module as an argument to identify the block being configured or viewed.
  • Used to construct the default HTML ID of "block-MODULE-DELTA" applied to each block when it is rendered. This ID may then be used for CSS styling or JavaScript programming.
  • Used to define a theming template suggestion of block_MODULE_DELTA, for advanced theming possibilities.

Module: Name of module creating that block. E.g: If you are creating the block from custom module than it will take the value of that module name.


To programatically create the block, you need to use hook_block_info(), hook_block_view() in your custom module something like below:

/**
 * Implements hook_block_info().
 */
function MyModule_block_info() {
  $blocks['test1'] = array(
    'info' => t('Block info 1'),
  );
  $blocks['test'] = array(
    'info' => t('Block info 2'),
  );

  return $blocks;
}


/**
 * Implements hook_block_view().
 */
function MyModule_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'test1':
      $block['content'] = 'Required content 1';
      break;

    case 'test2':
      $block['content'] = 'Required content  2';
      break;
  }

  return $block;
}
  • Thanks and do you know how can I apply my block to a specific page in the array key 'pages' => '', ? – mparryy Oct 18 '13 at 12:18
  • @mparryy you can pass the pages as 'pages' => 'node/8 node/9 node/10', You can check the pages column of block table, you will get the idea how the values are getting saved. – Ankit Agrawal Oct 18 '13 at 12:28

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.