Wednesday, October 11, 2006

Customizing Drupal form

By default, Drupal Form API would render each element per row. To alter the presentation, we have several ways. The simplest one is by defining #suffix, #prefix attributes in the form elements. The prefered one is by defining the theme function that would override the default presentation. Consider the following form definition:-

function customer_form($customer) {
  $form = array();
$form['name'] = array('#type' => 'textfield',
'#default_value' => $customer->name,
'#title' => 'Nama');
$form['address'] = array('#type' => 'textarea',
'#default_value' => $customer->address,
'#size' => 30,
'#title' => 'Alamat');
$form['postcode'] = array('#type' => 'textfield',
'#title' => t('Poskod'),
'#size' => 5,
'#maxlength' => 5,
'#default_value' => $customer->postcode);
$form['city'] = array('#type' => 'textfield',
'#title' => t('Bandar'),
'#size' => 30,
'#default_value' => $customer->city);
The form is build by the following function:-
function customer_new($customer) {
return drupal_get_form('customer_new', customer_form($customer));
So to override the default presentation, we define the theme function as `theme_form_id`:-
function theme_customer_new($form) {
$output = new Container;
$table = html_table();
$table->add_row(form_render($form['address']), form_render($form['city']), form_render($form['postcode']));
// render the rest of the elements
return $output->render();

This example make use PHPHtmllib library to build the HTML table.