Here is some sample code to help you further which adds a class on a field (field_image
) based on the value of another field (List field of type text
) (field_alignment
).
You will need to implement 2 preprocess hooks:
- On node
preprocess
to retrieve the objects / values of the fields and add extra datamember which contains the class value
- On field
preprocess
to retrieve the previously added extra datamember and merge it with the default classes_array
part of a field
function YOURTHEME_preprocess_node(&$variables)
{
if (!isset($variables['field_image']) || !isset($variables['field_alignment'])) {
return false; // if 1 of both fields is not available, don't do anything
}
$alignment = reset($variables['field_alignment']); // retrieve first item of array
$variables['content']['field_image']['#extra_classes'] = array($alignment['value']); // add an extra datamember containing an array with the value of the other field
}
function YOURTHEME_preprocess_field(&$variables)
{
$field = $variables['element'];
if ($field['#field_name'] !== 'field_image') {
return false; // only manipulate the image field
}
if (!isset($field['#extra_classes'])) {
return false; // don't do anything if the array with extra classes is not available
}
$variables['classes_array'] = array_merge(
$variables['classes_array'], $field['#extra_classes']); // merge the default field classes with the new added class
}
Update - When assigning class to field_image which sits within a field collection (named field_collection)
function YOURTHEME_preprocess_node(&$variables)
{
if (!isset($variables['field_collection']) || !isset($variables['field_classes'])) {
return false;
}
if (!isset($variables['content']['field_collection'])) {
return false;
}
$alignment = reset($variables['field_classes']);
foreach (element_children($variables['content']['field_collection']) as $index) {
foreach ($variables['content']['field_collection'][$index]['entity']['field_collection_item'] as &$field_collection_item) {
if (!isset($field_collection_item['field_image'])) {
continue;
}
$field_collection_item['field_image']['#extra_classes'] = array($alignment['value']);
}
}
}