3

Lets say I have a view called widgets.

On a given page, /widgets/manage/ I want to add use a function that calls drupal_add_js and drupal_add_css to change the behaviour and appearance.

If I wanted to make a change to the widget view in a theme, I'd change this file:

views-view--widgets--page.tpl.php

But, I want to change this in a module, so I can easily switch a feature on when I enable a module.

I don't need to add any other template files, I just want to call a few functions in PHP.

What is the best way to do this, and what would be the relevant hook to use here?

2
  • Define a hook_theme() as well, or it probably won't work. That always was the case. – user18075 Jun 4 '13 at 16:28
  • No need to implement hook_theme() unless you want to introduce new theme functions... – Clive Jun 4 '13 at 17:32
1

A template preprocess hook would be the best place. The naming convention for those functions is standard so you should be able to use

function MYMODULE_preprocess_views_view__widgets__page(&$vars) {
  drupal_add_js('...');
  drupal_add_css('...');
}
2
  • I've moved some code out of hook_init into the hook like this, and then cleared caches using drush cc all. Any idea what might be the cause of this not firing in this case? – mrchrisadams Jun 4 '13 at 16:28
  • I don't I'm afraid - if the name of the template file in the question works the preprocess should work as far as I know. Maybe try with MYMODULE_preprocess_view_view() to start with and see if you can confirm that's firing. In there inspect $vars['theme_hook_suggestions'], that should give you the names of template files that will be used (and subsequently which preprocess functions you can use) – Clive Jun 4 '13 at 17:33
0

In order to make a Views preprocess hook to work in a custom module, you should first kind of register it using mymodule_preprocess_views_view().

In mymodule.module file, add the following:

//Register your hook here
function mymodule_preprocess_views_view(&$vars)
{
    if (isset($vars['view']->name))
    {
      $function = 'mymodule_preprocess_views_view__'.$vars['view']->name;
      if (function_exists($function))
      {
        $function($vars);
      }
    }
}

//Preprocess hook for widgets-page view
function mymodule_preprocess_views_view__widgets__page(&$variables)
{
  $view = $variables['view'];
 //do your stuff here
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.