How to allow multiple blocks in a module of Drupal

若如初见. 提交于 2019-12-04 22:07:27

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