Last updated December 4, 2007. Created on December 4, 2007.
Edited by add1sun. Log in to edit this page.

In Drupal 5 you can add a custom theme function to the form element to accomplish this.

First we add #columns to our checkbox form element so we can use that as a variable and then we add a call to a custom theme function by adding #theme:

$form['checkboxes'] = array(
  '#type' => 'checkboxes',
  '#options' => $options,
  '#columns' => 4,
  '#theme' => 'columns_checkboxes',
);

Then add your theme function itself:

function theme_columns_checkboxes($e) {
  $options = $e['#options'];
  // Set the default if no columns are given.
  if (!isset($e['#columns'])) {
    $e['#columns'] = 8;
  }
  // Set the column number if less than the set amount.
  if (count($options) < $e['#columns']) {
    $e['#columns'] = count($options);
  }
  $rows = array();
  foreach ($options as $key=>$value) {
    $row[] = theme_checkbox($e[$key]);
    if (count($row) == $e['#columns']) {
      array_push($rows,$row);
      $row = array();
    }
  }
  // This flushes out the columns when the items don't divide evenly into the columns.
  if (count($row)) {
    array_push($rows,$row);
  }
  return theme_table(NULL, $rows);
}

This is pushing items into a theme_table function, but there are other ways to print them out. This method avoids having to keep track of too many variables and depend a little more on the core functions.

Here is an alternate way that doesn't use a table (note that this function is also not using the additional columns variable):

function theme_columns_checkbox($e) {
    $checkbox = '
'; $checkbox .= ''; if (!is_null($e['#title'])) { $checkbox .= ''.$e['#title'].''; } $checkbox .= "
\n"; unset($e['#title']); return $checkbox; }

Looking for support? Visit the Drupal.org forums, or join #drupal-support in IRC.

Comments

JaredAM’s picture

This example works fine in Drupal 6, but you need a hook_theme:

function mymodule_theme() {
  return array(
     'columns_checkboxes' => array(
        'arguments' => array(),
     ),
  );
}

In addition, when using the first example and calling theme_table, you may want to use array_pad to make sure the last row is complete.

if (count($row)){
  $pad = array_pad($row, $form['#columns'], "&nbsp;");
  array_push($rows,$pad);
}

In this way, the last row will have the correct number of cells.