How to allow multiple blocks in a module of Drupal

梦想的初衷 提交于 2019-12-06 16:23:22

问题


I am trying to make a module for Drupal 7 that provides a block and has certain configuration settings. Now what I want is that I want to provide 5 blocks to the user so that they can use different settings in each block. In other words, I want to provide each block a separate set of settings. How can I do that?

Edit: Actually I have made a module that shows a single block. If you have used superfish menu module then you can see there that they allow us an option to choose how many block should be made available. So that for each block we can use different menu to show. I am talking about that functionality


回答1:


Create a configuration page:

function my_module_admin_settings($form, &$form_state) {
  $form['my_module_number_of_blocks'] = array(
    '#title' => t('Post to Blog by default'),
    '#description' => t('Should content post to blog by default or only when selected?'),
    '#type' => 'select',
    '#options' => drupal_map_assoc(array(2, 3, 4, 5, 6, 7, 8, 9, 10)),
    '#default_value' => 2,
  );

  return system_settings_form($form);
}

You create blocks in a module using hook_block_info you define an array like:

hook_block_info() {
  number_blocks = variable_get('my_module_number_of_blocks', 0);
  $x=0
  while ($x < number_of_blocks) {
    $blocks['myblock-' . $x] = array(
      'info' => t('Block ' . $x), 
      'cache' => DRUPAL_NO_CACHE,
    );
  }
  return $blocks
}

You'll configure the values in hook_block_configure:

function hook_block_configure($delta = '') {
  // This example comes from node.module.
  $form = array();
  $parts = explode($delta, '-');

  if ($parts[0] == 'my_block') {
    $form['my_block_' . $parts[1] . '_option1'] = array(
      '#type' => 'select', 
      '#title' => t('Some option'), 
      '#default_value' => variable_get('my_block_' . $parts[1] . '_option1', 'first_option'), 
      '#options' => drupal_map_assoc(array('first option', 'second option')),
    );
  }
  return $form;
}

Once you have defined your blocks you need to tell them how to display with hook_block_view. Something like:

function hook_block_view($delta = '') {
  $block = array();
  $parts = explode($delta, '-');

  if ($parts[0] == 'myblock') {
    $block['subject'] = t('Block' . $parts[1]);
    $block['content'] = my_module_block_b_generate($parts[1]);
  }

  return $block;
}

Then you'll use the block number and configuration to determine the output:

my_module_block_b_generate($block_number) {
  $option1 = variable_get('my_block_' . $block_number . '_option1', 'first_option');

  return t('this is block ' . $block_number . '. It has chosen option ' . $option1 . ' for option1');
}


来源:https://stackoverflow.com/questions/12585912/how-to-allow-multiple-blocks-in-a-module-of-drupal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!