template_preprocess_field(&$variables, $hook) gives you the ability to manipulate fields before they are printed. Just like with template_preprocess_page()
and template_preprocess_node()
. Not sure what the $hook
parameter is for and I have never needed it myself.
Since this is a preprocess function that will be executed for each field, you should add a condition for your field name. Something like this will do:
function THEME_OR_MODULE_preprocess_field(&$variables) {
if($variables['element']['#field_name'] == 'FIELD_NAME') {
// Manipulate the data. use dsm() or print_r() to see the array structure.
}
}
Edit: It would seem as if $hook
is always passed as the string 'field', which would be quite useless. Can anyone confirm this?
Edit 2: Okey, so you actually don't need template_preprocess_field()
at all if you can override theme_field.
Below is a working example of a extended theme_field($variables) function based of the original version. There is also a good tutorial/example here, which @camcam shared in a comment.:
function THEME_NAME_field($vars) {
$output = '';
$i = 0;
// Render the label, if it's not hidden.
if (!$vars['label_hidden']) {
$output .= '<div class="field-label"' . $vars['title_attributes'] . '>' . $vars['label'] . ': </div>';
}
// Render the items.
$output .= '<div class="field-items"' . $vars['content_attributes'] . '>';
foreach ($vars['items'] as $delta => $item) {
$classes = 'field-item ' . ($delta % 2 ? 'odd' : 'even');
// Add Row index to classes and iteriate row index variable.
if ($vars['element']['#field_name'] == 'FIELD_NAME') {
$classes .= ' row-' . $i;
$i++;
}
$output .= '<div class="' . $classes . '"' . $vars['item_attributes'][$delta] . '>' . drupal_render($item) . '</div>';
}
$output .= '</div>';
// Render the top-level DIV.
$output = '<div class="' . $vars['classes'] . '"' . $vars['attributes'] . '>' . $output . '</div>';
return $output;
}
$hook
parameter when I have some time to spare.