drupal form api checkboxes

Tausif Khan picture Tausif Khan · Feb 10, 2011 · Viewed 8k times · Source

I am using drupal form api and using checkboxes. I am getting problem in default checked values with it. following is the code snippet...

$result = db_query("SELECT nid, filepath FROM {content_type_brand}, {files} WHERE content_type_brand.field_brand_image_fid
= files.fid");
        $items = array();
        while ($r = db_fetch_array($result)) {
                array_push($items, $r);
        }
        $options = array();
        foreach( $items as $i ) {
            $imagePath = base_path().$i['filepath'];
            $options[$i['nid']] = '<img src="'.$imagePath.'"></img>';
        }
        $form['favorite_brands'] = array (
            '#type' => 'fieldset',
            '#title' => t('Favorite Brands'),
            //'#weight' => 5,
            '#collapsible' => TRUE,
            '#collapsed' => FALSE,
        );
         $form['favorite_brands']['brands_options']
= array(
            '#type' => 'checkboxes',
            '#options' => $options,
            '#default_value' => $options_checked,// $options_checked is an array similar to $options but having elements which need to be checked by default...
            '#multicolumn' => array('width' => 3)
        );

but values are not checked by default... can anyone help what I am missing??

Thanks

Answer

psparrow picture psparrow · Apr 14, 2011

Your $options_checked array should not be in the same format as your $options array. Your $options array contains nid => img tag pairs. Your $options_checked array should simply contain the nid values of the options that should be checked by default:

$options_checked = array(8,17);