drupaldrupal-6drupal-fapidrupal-render

Drupal form in tabular layout


I am trying to render a tabular layout (html table) for a form such that first cell contains a checkbox.

$form = array();
$res = query('SELECT * FROM {mytable}');
$rows = array();
while($row = db_fetch_array($res)){
    $record = array();
    $checkbox = array(
        '#type' => 'checkbox',
        '#attributes' => array(
            'value' => $row['id'],
            'name' => 'myrecord[]',
        ),
    ); 

    $record[] = drupal_render($checkbox);
    $record[] = $row['other_field_1'];
    $record[] = $row['other_field_2']
    $rows[] = $record;
}

$form['records'] = array(
    '#value' => theme('table', array(), $rows);
);

return $form;

But all the rendered checkbox has output

<input type="checkbox" class="form-checkbox" name="" value="1" id="">
<input type="checkbox" class="form-checkbox" name="" value="1" id="">
<input type="checkbox" class="form-checkbox" name="" value="1" id="">
<input type="checkbox" class="form-checkbox" name="" value="1" id="">

What is the issue that name and value attributes are not getting applied on checkboxes?


Solution

  • The name and value is not something you can set using attributes, when using the form API. The name is related to the key of the form item, so if you had

    $form['pony'] = $checkbox;
    $form['yes'] = $checkbox;
    

    The first checkbox will have the name of pony while the second will have the name of yes. I believe that the value for checkboxes always is 1, but I'm not 100% sure.

    What you should do, to make this form properly, is to only create the form, in the form definition. Doing something like this:

    $form = array();
    $res = query('SELECT * FROM {mytable}');
    while($row = db_fetch_array($res)){
      $form[$row['id']] = array('#tree' => TRUE);
      $form[$row['id']]['checkbox'] = array('#type' => 'checkbox');
      $form[$row['id']]['other_field_1'] = array('#value' => $row['other_field_1']);
      $form[$row['id']]['other_field_2'] = array('#value' => $row['other_field_1']);
    }
    return $form;
    

    Doing something like this, you can create the table in a theme function for the form. Rendering the form elements in the theme function, will give them the correct name.