Presenting a Drupal form as a table

From ceejayoz

Jump to: navigation, search

This is more difficult than it should be. Once you figure it out, though, it's copy-pasteable.

function module_theme() {
  return array(
    'module_table_form' => array('argument' => array('form' => null)),
  );
}
 
function theme_module_table_form($form) {
  foreach(element_children($form) as $key) {
    // make sure this is one of our table rows
    if(isset($form[$key]['checkbox'])) {
      $row = array();
 
      // using drupal_render() on individual items takes manual control of these form elements
      $row[] = array('data' => drupal_render($form[$key]['checkbox']));
      $row[] = array('data' => drupal_render($form[$key]['something']));
      $row[] = array('data' => drupal_render($form[$key]['something_else']));
 
      $rows[] = $row;
    }
  }
 
  // build the header row
  $header = array(
    theme('table_select_header_cell'),
    'Something',
    'Something else',
  );
 
  // output the table
  $output .= theme('table', $header, $rows);
 
  // render any remaining form fields
  $output .= drupal_render($form);
  return $output;
}
 
function module_table_form(&$form_state) {
  $form = array();
  $form['#tree'] = true;
 
  // you'd probably populate the record from the database here, and step through them
  loop(something) {
    // add a checkbox (or any other field)
    $form[$record_id]['checkbox'] = array('#type' => 'checkbox');
 
    // other form elements or HTML
    $form[$record_id]['something']['#value'] = 'blah blah blah';
    $form[$record_id]['something_else']['#value'] = 'blah blah blah';
  }
 
  // submission buttons
  $form['buttons']['do_something'] = array(
    '#type' => 'submit',
    '#value' => 'Do something',
    '#submit' => array('module_submission_function'),
  );
 
  return $form;
}
Personal tools