2

I have a custom table in the Drupal DB, which I need to retrive and use on a few places on the site I'm creating. And I don't like to run soo much PHP in blocks, so I thought that I could get the table value I need, using PHP in template.php in the theme-dir and then just call the variable from a block, using PHP.

That didn't work.. Why and how should it be done?

template.php:

$sub_count = db_query("SELECT count FROM {sub_count}")->fetchField();

block:

<?php $sub_count; ?>
2

You need to use a preprocess function. Take a look at template_preprocess_block(). In your template.php you can use:

function YOURTHEME_preprocess_block(&$variables) {
  $variables['sub_count'] = db_query("SELECT count FROM {sub_count}")->fetchField();
}

and can print into the .tpl.php file as you did above.

A few good articles to learn more about preprocess functions are

As a basic overview of preprocess functions, from the second article:

Preprocess functions only apply to theming hooks implemented as templates. The main role of the preprocessor is to set up variables to be placed within the template (.tpl.php) files. Plain theme functions do not interact with preprocessors.

Notes:

  • Preprocessors are also used for providing template suggestions.
  • In versions 5 and below, the function _phptemplate_variables served the same purpose. It has been deprecated in 6.
  • Prior to Drupal 6.7, for your theme to have its preprocessors recognized, the template associated with the hook had to exist inside the theme. When a default template exists, copy it to your theme and clear the registry (or you should really be upgrading to a later version of Drupal anyway for security reasons, at which point you don't have to worry about this).
  • 2
    Thank you, but this means that I can't use a variable inside a block? – Daniel Holm Aug 7 '11 at 23:56

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.