10

My custom module defines a custom entity, which extends the EntityAPIController class. I managed to make it basically working, i.e. displaying fields etc via my custom tpl.php file. But I would like to create a mymodule_preprocess_entity function (as suggested here) to add custom variables to the tpl.php file. But such function is not running (is not called).

Also, when I display this entity, I noticed that the function template_preprocess_entity(&$variables) from entity.module is not running, either.

What else needs to be defined to make the preprocess function for custom entity being called?

| improve this question | | | | |
  • your using mymodule - the suggestion uses mytheme – rémy Mar 7 '13 at 13:43
9

I created a general mymodule_preprocess(&$variables, $hook) function and it showed that the specific function name should be mymodule_preprocess_myentity. Where myentity is the proper name of the entity.

So, this code is working for me:

function mymodule_preprocess(&$variables, $hook) {
  if (isset($variables['elements']['#entity_type'])) { // or maybe check for $hook name
    $function = __FUNCTION__ . '_' . $variables['elements']['#entity_type'];
    if (function_exists($function)) {
      $function($variables, $hook);
    }
  }
}

function mymodule_preprocess_myentity(&$vars) {
  ...
}
| improve this answer | | | | |
2

A more generic approach:

/**
 * Implements hook_preprocess().
 */
function mymodule_preprocess(&$variables, $hook) {
  if (isset($variables['elements']['#entity_type'])) {
    $myhook = "preprocess_{$variables['elements']['#entity_type']}_{$variables['elements']['#bundle']}_{$variables['elements']['#view_mode']}";
    $modules = module_implements($myhook);

    foreach ($modules as $module) {
      $function = "{$module}_{$myhook}";
      $function($variables);
    }
  }
}

Unfortunately module_implements() doesn't check if the active theme implements the preprocess hook.

| improve this answer | | | | |

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.