1

I'm using Drupal 7 with Bootstrap. I copied the sub-theme and renamed all the files accordingly and everything works fine, however I'm having problems with my sub-theme's template.php not doing what it should.

I am trying to add specific CSS classes to my form field while editing the form or adding new content. I tried following http://atendesigngroup.com/blog/adding-css-classes-fields-drupal, but I can't change the field's classses.

This is the code I have in template.php.

/**
 * Overrides theme_field()
 * Remove the hard coded classes so we can add them in preprocess functions.
 */

function MojCrm_field($variables) {
  $output = '';

  // Render the label, if it's not hidden.
  if (!$variables['label_hidden']) {
    $output .= '<div ' . $variables['title_attributes'] . '>' . $variables['label'] . ':&nbsp;</div>';
  }

  // Render the items.
  $output .= '<div ' . $variables['content_attributes'] . '>';
  foreach ($variables['items'] as $delta => $item) {
    $output .= '<div ' . $variables['item_attributes'][$delta] . '>' . drupal_render($item) . '</div>';
  }
  $output .= '</div>';

  // Render the top-level DIV.
  $output = '<div class="' . $variables['classes'] . '"' . $variables['attributes'] . '>' . $output . '</div>';

  return $output;
}

/**
 * Implements hook_preprocess_field()
 */

function MojCrm_preprocess_field(&$vars) {
  /* Set shortcut variables. Hooray for less typing! */
  $name = $vars['element']['#field_name'];
  $bundle = $vars['element']['#bundle'];
  $mode = $vars['element']['#view_mode'];
  $classes = &$vars['classes_array'];
  $title_classes = &$vars['title_attributes_array']['class'];
  $content_classes = &$vars['content_attributes_array']['class'];
  $item_classes = array();

  /* Global field classes */
  $classes[] = 'field-wrapper';
  $title_classes[] = 'field-label';
  $content_classes[] = 'field-items';
  $item_classes[] = 'field-item';


  /* Add specific classes to targeted fields */

  switch ($name) {
    case 'field_baza_direktor':
      $title_classes[] = 'inline';
      $content_classes[] = 'col-sm-6';
      break;
  }

}
  • 2
    Isn't $variables['classes'] an array? – beth Aug 22 '14 at 19:14
1

Using yourtheme_preprocess_field() won't work for forms because theme_field() isn't called. Instead, theme_form_element() is executed, which builds the form element wrapper. If you want to use/override the input itself override the corresponding theme function, e.g. theme_textfield() and so on.

Another way could be using hook_form_alter()/hook_FORMID_form_alter() if you want to override the attributes for a specific form only.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.