I've just started using Drupal after long experience of using other framework. When I do something new, I'm scaring to crash performance because of my incomprehension. So, my problem: I want to add dynamically some data from database to some existing page region. For example, I want to add list of child terms to taxonomy term page. And I don't need to change any other things on this page, so I don't want to turn on View. Is it normal to query data in preprocess functions? My solution for D7 was like this:

function mymodule_taxonomy_term_view_alter(&$build) {
  if ($build['#view_mode'] == 'full') {
    $children = taxonomy_get_tree($build['#term']->vid, $build['#term']->tid, 1);
    foreach($children as $term) {
      $build['children'][] = (array)$term;

function mymodule_preprocess_taxonomy_term(&$variables) {
  if($variables['vocabulary_machine_name'] == 'catalog') {

    if(count($variables['elements']['children'])) {
      $items = array();
      foreach($variables['elements']['children'] as $term) {
        $items[] = array(
          'data' => l($term['name'], 'taxonomy/term/' . $term['tid'])

      $variables['content']['children']['#markup'] = theme('item_list', array('items' => $items, 'title' => 'Text terms list', 'type' => 'ul', 'attributes' => array()));

Any comment are welcome.

1 Answer 1


No, it's not incorrect to query the database in a preprocess function. If the information is required to render the page, putting a query in a preprocess function is an acceptable choice. Plus, in this particular case taxonomy_get_tree() caches results, so there is very little cost associated with repeated fetches.

Regarding Views, yes there is some overhead associated with it, but it employs a sophisticated caching strategy, and is ultimately just so powerful and useful that most sites use it. You could probably solve this current problem with no custom code by using a Viewfield.

These questions provide a lot of interesting background on Drupal performance.

  • 3
    I agree; there is nothing wrong in querying the database in a preprocess function; if that would be wrong, then most of the Drupal functions should not be called, including the ones that cache the data, as by default Drupal caches the data using the database. It's then better to have such code in a preprocess function than in a template file.
    – apaderno
    Aug 12, 2011 at 15:05
  • «You could probably solve this current problem with no custom code by using a Viewfield.» — Thank you, that was useful)
    – kalabro
    Aug 13, 2011 at 12:53

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.