Question:

D7 Custom Module: Turning tabs into contextual links

Isaac: 2 weeks ago

Created a module (D7) that turns every nodes edit tabs into contextual links instead. Works great... But on the first initial load to the page I get a warning. Disappears after I refresh once. Then it comes back around surfing to another page and back again.

Warning: Invalid argument supplied for foreach() 
in mytheme_contextual_contextual_links_view_alter() 
line 19....

Driving me bonkers. Code below. It's having an issue with my foreach($tabs as $tab)...

  function mytheme_contextual_block_view_system_main_alter(&$data, $block) {
      if (user_access('access contextual links')) {
        $tabs = menu_primary_local_tasks();
        $data['content']['#contextual_links']['block'] = array(
          'admin/structure/block/manage',
          array('system', 'main'),
        );
      }
  }

  function mytheme_contextual_contextual_links_view_alter(&$element, &$items) {
      if (arg(2) != 'edit' && arg(3) != 'edit' && arg(0) != 'admin' && arg(1) != 'add') {
        if (isset($element['#element']['#block']) && $element['#element']['#block']->delta == "main") {
          $tabs = menu_primary_local_tasks();
          foreach( $tabs as $tab ){
              $element['#links'][$tab['#link']['path']] = array(
                'title' => $tab['#link']['title'],
                'href' => url($tab['#link']['href'], array('absolute' => TRUE)),
              );
          }
        }
      }
  }

  function mytheme_contextual_preprocess_page(&$variables) {
      if (arg(2) != 'edit' && arg(3) != 'edit' && arg(0) != 'admin' && arg(1) != 'add') {
        $variables['tabs']['#primary'] = array();
      } 
  }

Answer:
Arya: 2 weeks ago

Place the for loop inside an if statement

$tabs = menu_primary_local_tasks();
if($tabs)
{
      foreach( $tabs as $tab ){
          $element['#links'][$tab['#link']['path']] = array(
            'title' => $tab['#link']['title'],
            'href' => url($tab['#link']['href'], array('absolute' => TRUE)),
          );
      }
}