1

All I see are classes, and from my understanding seems that there is nothing in the variables.

1 Answer 1

3

By default template_preprocess_field doesn't initialize the attributes array, so you don't see it when viewing the variables with the Devel module. You can achieve this and any other attributes by adding it in a template_preprocess_field() from your themes template.php file. When added it will get output to the field in template_process_field(). Here's a generic example of adding an attribute to a field. Swap all caps items for your use case...

/**
 * Implements hook_preprocess_field().
 */
function THEMENAME_preprocess_field(&$variables) {
  $content_type = $variables['element']['#bundle'];
  $view_mode = $variables['element']['#view_mode'];
  $field_name = $variables['element']['#field_name'];

  switch ($field_name) {
    // We make sure it only effects the correct field ...
    case 'FIELD_MACHINE_NAME':

      // ... and, assuming you want to limit the where an id is used, we only add on a certain content type's full node page.
      if ($view_mode === 'full' && $content_type === 'CONTENT_TYPE_MACHINE_NAME') {
          $variables['attributes_array']['id'] = 'my-id';
      }
      break;
  }
}
4
  • Thank you. Am I right in understanding I have to do the switch/break cycle for all my fields? Any way to address all fields in the specific content type at once? No problem in doing as you suggested, but I have 30+ fields to address. I'll try this tomorrow, please be patient for I'll report back.
    – keneso
    Mar 8, 2015 at 0:12
  • Great, I had no doubts about it working, just repeated the case/break snip for all my fields.
    – keneso
    Mar 8, 2015 at 12:53
  • You could change the switch to test for the $content_type variable, change the case to the content type machine name and remove the content type check within the case statement. That would allow this code to run on every field at once. In that case you would want a more programatic way of assigning an ID, like using the field's css name... $variables['attributes_array']['id'] = $variables['field_name_css']; ... A couple huge notes on this. One, if a field shows up twice on a page you'll have invalid html. Two, ID's are for javascript hooks. Use the class for styling. Mar 9, 2015 at 2:45
  • Thank you. I am using the IDs for anchors inside the page. I have done most of the fields with the single switch, but I'll try your second suggestion for learning. I'm sorry I can't upvote you as I don't have enough points.
    – keneso
    Mar 9, 2015 at 10:55

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.