Skip to main content
knackforge blog knowledge base

How to add contextual link on a block

Contextual link is a nice addition made into Drupal 7 to favor usability. It offers, quick links to pages performing administrative operations. By default it is available for core block and node teaser view. But designed to be made extendable for other items too - Views, panels, and so.
 
Custom contextual link (aka ccl) module is the best choice for adding custom link items.
 
But I have faced some problems in ccl module while adding a custom contextual link for a block. I would like to share the problems and how I overcame the same.
 
ccl relies on hook_contextual_links_view_alter() which will only alter or add links if there is already a #contextual_links element in the renderable array. The main content block doesn't get the default Configure block contextual link (see _block_get_renderable_array()), and therefore ccl doesn't affect it by default. 
 
In my case I have added the block on a panel, So the ccl modules doesn't affect my block. So I had to find a workaround. Problem explained in detail below,
 
I needed to create a contextual link for my follow block (from Follow module). The destination of the link is admin/config/services/follow. Then we have to create a menu for contextual link with the path in hook_menu()
 
/**
 * Implements hook_menu()
 */
function MY_MODULE_menu() {
  $items['admin/config/services/follow/configure'] = array(
    'title' => t('Edit follow'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'context' => MENU_CONTEXT_INLINE,
  );
return $items;
}
 
After that  we need to add the new contextual link in block's content using hook_block_view_MODULE_DELTA_alter()
 
/**
 * Implements hook_block_view_MODULE_DELTA_alter()
 */
function mymodule_block_view_follow_site_alter(&$data, $block) {
  $data['content']['#contextual_links']['follow'] = array(
    'admin/config/services/follow', array('follow', 'site'),
  );
}
 
Hooray! I got a new contextual link on my follow block. The same trick would work for other cases too. For example to add a contextual link to main menu.