Is it possible to set multiple default values using the #default_value attribute for a checkboxes or multi-select form control? If so could somebody post an example for how to do this?

Comments

nevets’s picture

You want to set up an array of values for the #default_value. The trick is the value of each default value is the index of the options array.

So for example if you have

$options = array(12 => 'blue', 23 => 'red', 35 => 'green');

if blue and green are default values you would have

$existing = array(12, 35);

and the code to produce the form field something like

	$form['field_name'] = array(
		'#type' => 'checkboxes',
		'#title' => 'Field Title',
		'#options' => $options,
		'#default_value' => $existing,
		'#description' => t('Field Help.')
	);
sandeshyadav’s picture

It worked and saved my day . Thanks a lot .
What I did was
$existing = array(12 => 12, 23 => 23, 35 => 35);

dskanth’s picture

When i am editing the node content, i tried to populate a multiselect field with values from the database, and it worked for me when i specified both the #options and #default_value with the same array in my form code:

$form['field_abc']['und']['#options'] = $array;
$form['field_abc']['und']['#default_value'] = $array;

nevets’s picture

Note this would mean all the options are on/selected by default