8

I'm building a Drupal 7 module to create a bespoke field type. I've implemented all the required hooks. My hook_field_formatter_view() function looks like this:

function MYMODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  switch ($display['type']) {
    case 'default':
      foreach ($items as $delta => $item) {
                $element[$delta] = array(
                  '#theme' => 'test',
                  '#item' => $item,
                );
      }
      break;
  }

  return $element;  
}

I've then defined the theme() function below:

function theme_test($variables) {
    return '<h1>Hello World</h1>';
}

But when I view the page nothing is output. If I look at the recent log entries I see this message:

Theme key 'test' not found.

If I change my MYMODULE_field_formatter_view render array '#theme' value to a built in theme function like 'item_list' it works. But for some reason my custom theme function is not being picked up.

I've rebuilt the theme registry hundreds of times as well as cleared the caches.

3 Answers 3

12

You probably have not defined your theme hook in hook_theme().

The Using the theme layer section of the Development handbook has an in-depth discussion about this.

2
  • Spot on, I keep getting caught out by these little changes from Drupal 6 to Drupal 7!
    – Camsoft
    May 4, 2011 at 12:49
  • 4
    Theme functions must be registered too in Drupal 6.
    – Berdir
    May 4, 2011 at 13:33
10

You need to define the theme function in hook_theme and then clear the cache.

 function MYMODULE_theme() {
   return array(
     'test' => array (
       'render element' => 'element',
     ),
   );
 }
2

I was facing the same issue where my custom theme function was never being called in my template, even though it was registered. When I switched to another theme, it worked.

My solution was re-naming theme into 'something_theme', because I made a stupid mistake and already had module named 'something'.

Module and theme should never have the same name, because it leads into collision which causes unexpected behavior and hook overriding.

Your Answer

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

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