How to create multiple blocks programatically in Drupal 8

Created on 16 July 2018, almost 6 years ago
Updated 2 May 2024, 2 months ago

I would like to create multiple blocks using the data rendered from the variable table in Drupal 8. I was able to achieve it in Drupal 7, but I can't find a way to do the same in Drupal 8.

Code for Drupal 7 is as follows:

/**
 * Create a block that will display the calendar feed
 * Implements hook_block_info
 */
function my_module_block_info() {
  $blocks = array();
  $block_urls = variable_get('my_module_content');
  $block_regions = variable_get('my_module_content_block_region');
  $number_of_blocks = count($block_urls);
  if ( $number_of_blocks > 0 ) {
    foreach ( $block_urls as $key => $block_url ) {
      $blocks['eventblock-' . $key] = array(
        'info' => t('my_module_widget_block_' . $key), 
        'status' => TRUE,
        'region' => $block_regions[$key],
        'cache' => DRUPAL_NO_CACHE,
      );
    }
  }
  return $blocks;
}

/**
 * Render the my_module block
 * Implements hook_block_view
 */
function my_module_block_view($delta = '') {
  $block = array();
  $block_urls = variable_get('my_module_content' , array());
    foreach ( $block_urls as $key => $block_url ) {
      switch ($delta) {
        case 'eventblock-' . $key:
          $widgetURL= $block_urls[$key];
          $block['content'] = my_module_content_generate($widgetURL); // Some function to generate block content.
          break;
        }
    }

  return $block;
}

Using the below solution I was able to create multiple blocks but all of them have same ID.

https://drupal.stackexchange.com/a/264178/71454

I cant find a way or documentation to change the block Id of the created blocks.
In Drupal 7 I was able to assign Block Region using the key 'region' but cant find a way to do Same in Drupal 8.
Can anyone please help to port the Drupal 7 code to Drupal 8 .

💬 Support request
Status

Closed: won't fix

Component

Missing documentation

Created by

🇮🇳India miststudent2011

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.69.0 2024