Monday, December 14, 2009

How to theme a Drupal form

This tutorial has been revised significantly to provide a robust solution consistently works.
Define a function named your_theme_name_ or phptemplate_ plus name_of_form($form).
  • Tip: You can find out what the names of forms are by implementing hook_form_alter in a module and adding the code drupal_set_message("Form ID: " . $form_id);, as in the first commented out line in this example.
function phptemplate_user_register($form) {
   
$variables = array('user' => $user, 'form' => $form);
    return
_phptemplate_callback('user_register', $variables);
}
?>
Then create a .tpl.php file with that name.
In this case, user_register.tpl.php
We can use this PHP snippet:

drupal_set_message('< pre >'. var_export($variables,TRUE) .'< /pre >');
?>
This provides us with the variable names (inside the $form variable) that are available to "drupal render" at your own chosen place.
  • Tip: To preserve the functionality of Drupal's catch-all-remaining form elements, you must pass the the form values in from template.php in a broader variables array (as described above). This allows you to use a form variable with form element names as keys, rather than using form names directly. Form names directly will build the form, but without the ability to drupal_render all remaining form elements, and several hidden ones are essential to a functioning Drupal form.
Example of a form theming .tpl.php file:






My Story

print drupal_render($form['field_storypic']); ?>

print drupal_render($form['field_user_story_field']); ?>




print drupal_render($form['captcha']); ?>

print drupal_render($form['submit']); ?>

unset($form['field_mostimportantlesson']);
print
drupal_render($form);
?>
Note the last step: we unset any fields we don't want to show, and then print the remainder of the form. If you drupal_render($form) outputs something you don't want or in a place you don't want it, simply unset that field or drupal_render that field specifically where you do want it.

Modifying individual fields

That's great, we can put fields in any order, surround them with any markup we want, and skip ones we don't want. What about changing the output of a given field?
We will only discuss here the simple way, very similar to form_alter, yet powerful enough to almost certainly meet all your needs with the addition of CSS.
In this case, we want to do something special with the age at diagnosis field.
To see what we're doing and make an initial attempt which proved incorrect, we added this to our user_register.tpl.php file in our theme's directory:

drupal_set_message('
'.print_r($form['field_ageatdiagnosis'],TRUE).'
'
);
$form['field_ageatdiagnosis']['#suffix'] = ' '. t('years');
print
drupal_render($form['field_ageatdiagnosis']);
?>
That printed "years" at the end of the whole form, not what we had hoped. We will be able to refine our attempt based on the output of drupal_set_message print_r on the field, below:
Array
(
    [#tree] => 1
    [0] => Array
        (
            [value] => Array
                (
                    [#type] => textfield
                    [#title] => Age at Diagnosis
                    [#default_value] => 
                    [#required] => 0
                    [#description] => 
                    [#size] => 20
                    [#maxlength] => 11
                    [#attributes] => Array
                        (
                            [class] => number
                        )

                    [#field_prefix] => 
                    [#field_suffix] => 
                    [#post] => Array
                        (
                        )

                    [#programmed] => 
                    [#tree] => 1
                    [#parents] => Array
                        (
                            [0] => field_ageatdiagnosis
                            [1] => 0
                            [2] => value
                        )

                    [#weight] => 0
                    [#processed] => 
                    [#input] => 1
                    [#autocomplete_path] => 
                    [#name] => field_ageatdiagnosis[0][value]
                    [#id] => edit-field-ageatdiagnosis-0-value
                    [#value] => 
                    [#sorted] => 1
                )

            [#post] => Array
                (
                )

            [#programmed] => 
            [#tree] => 1
            [#parents] => Array
                (
                    [0] => field_ageatdiagnosis
                    [1] => 0
                )

            [#weight] => 0
            [#processed] => 
            [#sorted] => 1
        )

    [#post] => Array
        (
        )

    [#programmed] => 
    [#parents] => Array
        (
            [0] => field_ageatdiagnosis
        )

    [#weight] => 0.011
    [#processed] => 
    [#sorted] => 1
)
Based on this information, we revised our PHP to set #field_suffix:
$form['field_ageatdiagnosis'][0]['value']['#field_suffix'] = t('years');
$form['field_ageatdiagnosis'][0]['value']['#attributes'] = array('class' => 'number inline');
print
drupal_render($form['field_ageatdiagnosis']);
?>
We could set #title and #size the same way.
As shown above, we can even add new classes by modifying the #attributes value (noting that in this case the number class was set in the #attributes array, and we would not want to unset it, so we list it again while adding the class inline):
Note: If you look at the HTML output for a form field, you may see additional classes. For instance, 'form-text' is supplied automatically by Drupal form_rendering, and does not need to be restated when adding a class attribute. Using the drupal_set_message('
'.print_r($form['field_ageatdiagnosis'],TRUE).'
'); trick to see what's there is a very good idea to make sure you don't overwrite any important attribute. References:

No comments: