Write the value of a field as a css class to another field Could someone point me in the right direction to write the value of a field A to the css classes array of field B?

In my case I'm using a field collection (with text and file/image field, to make a sort of paragraph) and want to make a select field (with 4 preset options) so the node creator can choose if they want the file/image field displayed top, left, or right.

I don't really want to mess around with dynamic views or special formatters, just write the value of my select list to the class of the file/image field wrapper.
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(&amp;$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(&amp;$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(&amp;$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 &amp;$field_collection_item) {
              if (!isset($field_collection_item['field_image'])) {
                  continue;
              } 

              $field_collection_item['field_image']['#extra_classes'] = array($alignment['value']);
         }
    }
}