Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I call my theme preprocess function for a specific field?

i'm on Drupal 7 and i have aspecific tpl.php file for a content field_image: "field--field_image.tpl.php". I need to create a preprocess function for this field and for my theme.

Supposing my theme name is "My Theme"

It should look like

function my_theme_preprocess_field(&$variables, $hook) {
  $variables['classes_array'][] = 'aClassName';
}

but it doesn't work. I am wrong. But where?

Thanks

like image 567
sibest Avatar asked Sep 28 '11 10:09

sibest


2 Answers

You can use template_preprocess_field() (like you do in your code above) but just test the particular field is the right one for you:

function my_theme_preprocess_field(&$variables, $hook) {
  $element = $variables['element'];
  if (isset($element['#field_name'])) {
    if ($element['#field_name'] == 'field_image') {
      $variables['classes_array'][] = 'aClassName';
    }
  }
}

Once you've implemented the hook don't forget to clear your caches, hook implementations are cached in Drupal 7 so won't be picked up until the cache is cleared.

like image 151
Clive Avatar answered Oct 23 '22 08:10

Clive


You could declare a mytheme_preprocess_field(&$variables, $hook) in your theme's template.php where you can check your field and do operations on its label or markup, add classes, anything. So you wouldn't need field specific tpls. - eg.

function mytheme_preprocess_field(&$variables, $hook) {
  if ($variables['element']['#field_name'] == 'field_machine_name') {
        $variables['items'][0]['#markup'] = 'add custom markup';
  }
}

Hope this helps someone.

like image 44
SGhosh Avatar answered Oct 23 '22 09:10

SGhosh