Is possible for a module to know when one of its blocks is being output on the dashboard, and change the content of that block?

drupal.stackexchange https://drupal.stackexchange.com/questions/514

  •  16-10-2019
  •  | 
  •  

Question

Drupal 7 has a new core module (dashboard.module) that allows users with the right permissions to add blocks defined from third-party sites to the dashboard, which is shown as overlay on the current page.

Is it possible for a module that implements blocks to know when the block is being rendered on the dashboard?
The idea would be to change the content of the block, and make it smaller (for example).

Was it helpful?

Solution 2

Looking at the code of dashboard.module, I found the following function:

/**
 * Implements hook_block_list_alter().
 *
 * Skip rendering dashboard blocks when not on the dashboard page itself. This
 * prevents expensive dashboard blocks from causing performance issues on pages
 * where they will never be displayed.
 */
function dashboard_block_list_alter(&$blocks) {
  if (!dashboard_is_visible()) {
    foreach ($blocks as $key => $block) {
      if (in_array($block->region, dashboard_regions())) {
        unset($blocks[$key]);
      }
    }
  }
}

dashboard_is_visible() is the function that returns TRUE when the dashboard is visible, and dashboard_regions() is the function that returns an array containing the list of the regions contained in the dashboard.

Those are the functions that allows to a module to know when its blocks are being rendered in the dashboard. The only problem is for the module to know to which region its blocks are associated, as the block object is not passed to the hook_block_view(). Drupal 7 uses new hooks, hook_block_view_alter() and hook_block_view_MODULE_DELTA_alter(), whose second parameter is the block object. Implementing one of these hooks is possible to alter the block basing on the fact the block is being rendered in the dashboard, or not.

Supposing that mymodule is the module short name, and test_block is the delta value, the module should use the following function:

/**
 * Implements hook_block_view_MODULE_DELTA_alter().
 */
function mymodule_block_view_mymodule_test_block_alter(&$data, $block) {
  if (dashboard_is_visible() && in_array($block->region, dashboard_regions())) {
    // The block is rendered in the dashboard.
  }
}

OTHER TIPS

You could check the url argument that the block is displayed on and then if it matches an expected pattern i.e. /dashboard then you can alter the contents of the block. This solution only really works if you've coded the block yourself.

Update: This method will still work, although I'm not familiar enough drupal 7s dashboard module to comment further. The only thing I would suggest is to output page variables and see if there is anything set by dashboard module.

Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top