1

In Drupal 7, you can put the following code in template.php to add the class 'vr-paragraphs' to the field called 'field_title'

function THEMENAME_form_alter(&$form, &$form_state, $form_id) {
       $form['field_title']['#attributes']['class'][] = 'vr-paragraphs';
}

How can I modify this code to target all fields on the form and not just 'field_title'.

Also, this code only adds the class to the form-wrapper part of the filed. How can I alter the label part?

Thanks for any help!

2 Answers 2

3

When you need to find the child items present in a form, you need to use element_children(), as Drupal functions like filter_process_format() do.

The reason is simple: In a Drupal form array, as well as in a render array, not all the keys are child items; those keys with a name that starts with # are properties. Consider, for example, the form returned from forum_form_forum(); if you loop through it with the following code, you would add values where you should not.

foreach($form as $key => $value) {
  $form[$key]['#attributes']['class'][] = 'vr-paragraphs';
}

In fact, $form['#submit'] is not a child item, nor is $form['#theme']. In particular, when your code will be executed for the last key, you would get a PHP error. $form['#theme'] is a string, and $form['#theme']['#attributes'] would select a character of that string, supposing that '#attributes' would be evaluated as the integer 0; even in that case, $form['#theme']['#attributes']['class'][] would not be a valid PHP construct.

The correct code would be the following one.

foreach(element_children($form) as $key) {
  $form[$key]['#attributes']['class'][] = 'vr-paragraphs';
}
0
-1

Implement a for loop over each form field to add the class. eg.

foreach(form as $key => $value){
  $form[$key]['#attributes']['class'][] = 'vr-paragraphs';
}

You may have to check if it is actually a field though, maybe by checking if $form[$key]['#title'] is set.

If I remember correctly, the label is usually taken from the '#title' of the field.

2
  • Thanks for your help. This is what I have tried: function THEMENAME_form_alter(&$form, &$form_state, $form_id) { foreach(form as $key => $value){ $form[$key]['#attributes']['class'][] = 'vr-paragraphs'; } } But it doesn't seem to work. Am I doing something wrong?
    – big_smile
    Feb 9, 2013 at 16:41
  • The answer posted by kiamlaluno should work, use that.
    – 2pha
    Feb 10, 2013 at 3:54

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.