2

I want a hook that will let me conditionally add js/css to the page depending on the type of entity.

Since I am putting this in a module I cannot use a theme hook (because if the theme already defines the hook then Drupal will crash).

Ultimately, I want to do something like:

// SWTICH BY ENTITY TYPE
switch($entity_type){
    case 'eform':  // entity forms
        drupal_add_js( $theme_path . '/scripts/ajax_forms.js');
        break;
    case 'view':  // view pages (making this one up)
        drupal_add_js( $theme_path . '/scripts/fancybox.js');
        break;
}
// SWTICH BY CONTENT TYPE
switch($content_type){
    case 'services':
        drupal_add_js( $theme_path . '/scripts/fancybox.js');
        break;
}
// SWITCH BY NID
switch($nid){
    case '293': // Homepage
        drupal_add_js( $theme_path . '/js/global.js');
        break;
}

Right now I'm using hook_node_view to check content type & nid. Works great for nodes, but doesn't help me with non-nodes.

1 Answer 1

1

hook_entity_view() should do the trick

Act on entities being assembled before rendering.

e.g.

function MYMODULE_entity_view($entity, $type, $view_mode, $langcode) {
  switch ($type) {
    case 'node':
      ...
      break;
  }
}
2
  • This works on most pages, but is not firing on my entityform page. I'm surprised - I don't see why this wouldn't work..
    – doub1ejack
    Commented Feb 6, 2014 at 15:58
  • 1
    Yeah it won't work for forms as they're the 'edit' op instead of 'view'. hook_form_alter() might be your best option, you should be able to inspect the $form array and find out if has an entity attached (usually in $form['#entity']
    – Clive
    Commented Feb 10, 2014 at 17:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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