CTools Include sometimes doesn't work

280 views Asked by At

So using the drupal include function for a dropdown works, but on certain pages the scripts are not included and there is no error thrown anywhere. This happens inside hook_block_view. On the actual page, Drupal.behaviors.CToolsDropdown is missing on pages it does't work on. But no indication as to why.

ctools_include('dropdown.theme');
...
$block['content'] = array(
      '#markup' => theme_ctools_dropdown($vars),
);
1

There are 1 answers

4
bbujisic On BEST ANSWER

ctools_include() loaded the dropdown.theme.inc file, and we know that because otherwise, invoking theme_ctools_dropdown() would result in fatal error due to the call to undefined function.

theme_ctools_dropdown() itself unconditionally adds the needed dropdown.js and dropdown.css files.

So I believe that your code never gets invoked on these pages (i.e the block does not get to be displayed). To prove that, squeeze in a drupal_set_message('Hello world'); somewhere in your hook_block_view() and see what will happen.

If you see the message, search for hook_js_alter() in your code, maybe there's a logic somewhere which removes dropdown.js on those pages.

Update: drupal_add_js() called within the block won't be included after clearing caches. So you need to include JS and CSS files using #attached property:

ctools_include('dropdown.theme');
// ...
$block['content'] = array(
  '#markup' => theme_ctools_dropdown($vars),
  '#attached' => array(
    'css' => array(
      drupal_get_path('module', 'ctools') . '/css/dropdown.css',
    ),
    'js' => array(
      drupal_get_path('module', 'ctools') . '/js/dropdown.js',
    ),
  ),
);