Trying to do something really simple : default a checkbox to 'checked'.

Here's my code :

$form['item'][$item->iid]['check'] = array(
'#type' => 'checkbox',
'#default_value' => 1,
'#prefix' => "<div class=\"publish_checkbox\"",
'#suffix' => "</div>",
);

output: <input type="checkbox" name="check" id="edit-check" value="1" class="form-checkbox" />

Checkbox isnt checked by default, but pass its state (0,1) as expected. Notice the lack of checked="checked".

Adding '#value' => 1

output: <input type="checkbox" name="check" id="edit-check" value="1" checked="checked" class="form-checkbox" />

Checkbox is checked by default, but only outputs 1, as the documentation states.

So I can have it checked by default, but non-functional. Anyone have ideas

Comments

FiReaNGeL’s picture

Fixed it with an #attributes array('checked' => 'checked'), but I was expecting it to do it by itself, detecting that #default_value isn't 0 :) Oh well, problem fixed.

---
Biology News Net

jaxxed’s picture

I can't see how #default_value has any impact on #type=>checkbox. If I'm wrong then ignore my comments here.

I'm not sure why the FormAPI indicates that you can use #default_value. I get the same problem described above and when I looked at the form control code for checkbox I see the following:

function theme_checkbox($element) {
  _form_set_class($element, array('form-checkbox'));
  $checkbox = '<input ';
  $checkbox .= 'type="checkbox" ';
  $checkbox .= 'name="'. $element['#name'] .'" ';
  $checkbox .= 'id="'. $element['#id'].'" ' ;
  $checkbox .= 'value="'. $element['#return_value'] .'" ';
  $checkbox .= $element['#value'] ? ' checked="checked" ' : ' ';
  $checkbox .= drupal_attributes($element['#attributes']) . ' />';

  if (!is_null($element['#title'])) {
    $checkbox = '<label class="option">'. $checkbox .' '. $element['#title'] .'</label>';
  }

  unset($element['#title']);
  return theme('form_element', $element, $checkbox);
}

It looks to me like #default_value isn't referenced at all. This seems to me to be something that should be fixed when values are assigned. Look at line 688 of form.inc:

  $form['#value'] = !empty($edit) ? $form['#return_value'] : 0;

There is no way differentiate between an unchecked checkbox and a situation where no form is submitted because this function (form_builder) passes only the part of the $_POST array pertaining to this control. What we need is form ['#value'] to be differentiable between unchecked and unsubmitted (unsubmitted=>null,unchecked=>0). Then we could do a trade off between #default_value and #value:
Form Values should be one way if no form was submitted and another way if no value is submitted.

  // form.inc : form_builder
  static $noform = (bool)count((array)$form_values);
  $form['#value'] = !empty($edit) ? $form['#return_value'] : ($noform?'':0);

  // form.inc : theme_checkbox
  $checkbox .= (isset($element['#value'])?($element['#value']?' checked="checked"':''):($element['#default_value']?'checked="checked"':''));

I guess for now you could overload the checkbox theme and add the $noform into the theme

Enough chatter from me. Let the experts speak

jaxxed’s picture

I forgot to mention that I am using drupal 5.1, php 5

gemini’s picture

I think I'm having a similar problem.

Default value is 1 even if we don't set it up manually. When I use the value of the checkbox to insert or update my table - it's always 1 no matter if the checkbox is checked or unchecked. I need to write value 0 if it's unchecked and value 1 only when it's checked... how would I do that?

Thanks in advance!

seren10pity’s picture

I've got a different theme for admin, and tried to alter my theme settings form :
I needed to check some boxes depending on theme variables.

when I printed my theme settings form, and theme settings vars, it was printed twice, with different theme settings vars, the second ones always returning false. And the corresponding checkboxes, that were having #defautl_value => theme_get_settings('my_var') were never checked.

It comes from the fact that the default theme and settings were loaded first, returning the good values in theme_get_settings('mySetting') ; but the admin theme was loaded then, and didn't found these vars in its settings, so returned false for all of them.

I solved the problem using theme_get_settings('my_var', <strong>'my_theme'</strong>).

this way, it always returned the right values, and in consequence, my checkboxes were checked by default.

I know my case is a bit specific, due to the fact that it has a different admin theme, and is on an admin page ; bit I hope it helps.

Heine’s picture

I have no such problem; a checkbox with #default_value set to 1, displays checked.

You may want to close the div in #prefix though.
--
The Manual | Troubleshooting FAQ | Tips for posting | How to report a security issue.

FiReaNGeL’s picture

Good catch about the missing closing tag for my prefix div, thanks!

Could my problem be related to the said checkbox be part of the 2nd page of a multipage dynamic wizard-like form? I'll try to find where the problem is coming from.

---
Biology News Net

mjs-1’s picture

I had a similar problem and this mistake I initially made was not passing the values from the first part of the form to the second. I was able to solve it doing so.

As an example

  switch ($step) {
    case 1:

						
		$form[test] = array(
			'#type' => 'checkbox',
			'#title' => t('Select Value'));
	break;

	case 2:
	
		$test =  $form_values['test'];
			
		$form[test] = array(
			'#type' => 'checkbox',
			'#title' => t('Select Value'));

mikelove’s picture

I had the same problem and was working on it for a while. thanks for this.

RobertNelsonVance’s picture

Could someone provide further example of how to override comment_form?

http://api.drupal.org/api/function/comment_form/5

Specifically, I am looking in the comment.module to replace....

$form['name'] = array('#type' => 'textfield', '#title' => t('Your name'), '#maxlength' => 60, '#size' => 30, '#default_value' => $edit['name'] ? $edit['name'] : variable_get('anonymous', t('Anonymous')), '#required' => TRUE);

with....

$form['name'] = array('#type' => 'textfield', '#title' => t('Your name'), '#maxlength' => 60, '#size' => 30, '#required' => TRUE);

I tried adding to my "template.php" file....

function phptemplate_comment_form($form) {
   return _phptemplate_callback('comment-form', array('form' => $form));
}

and created a "comment-form.tpl.php" file....

<?php 
$form['name'] = array('#type' => 'textfield', '#title' => t('Your name'), '#maxlength' => 60, '#size' => 30, '#required' => TRUE);
print drupal_render($form);
?>

This eliminates the "Anonymous" pre-fill default value from the field when the page is loaded, but it also results in the following error....

warning: implode() [function.implode]: Invalid arguments passed in /home/.watson/username/domain/includes/form.inc on line 623.

I also tried the following in my "comment-form.tpl.php" file....

<?php 
$form['name']['#default_value'] = 'test';
print drupal_render($form);
?>

and this didn't seem to do anything.

I am guessing that, because I am still learning this, it is a syntax error on my part.

I tried following the examples on http://api.drupal.org/api/file/developer/topics/forms_api.html/5 but am apparently missing something.

Thanks for any help!

Heine’s picture

You need to make a module and implement hook_form_alter to modify initial form values.

Example for Drupal 5:

function mymodule_form_alter($form_id, &$form) {
  if ($form_id == 'comment_form') {
    $form['name']['#default_value'] = 'another default value';
  }
}

You will need additional checks (eg check author) to make sure changing default_value of name is appropriate.

--
The Manual | Troubleshooting FAQ | Tips for posting | How to report a security issue.

RobertNelsonVance’s picture

WoW. I didn't think of that. I'm just surprised that I am the only one that seems to have wanted to do this. It seems to me that someone else would have already wanted to do this and have documented it somewhere with an already complete solution. I was hoping to be able to just "drag and drop" something that someone already contributed : ) Well, if I come up with something or find something, I'll share it with everyone. Thanks.

lukas.fischer’s picture

<?
foreach (customportal_api_loadportals() as $node) {
		$portal_formatted[$node->nid] = $node->title;
		if (customportal_api_ismemberof(arg(1), $node->nid)) {
			$portal_ismember[] = $node->nid;//;
		}
	}
	$form['portal_access']['portal_member'] = array(
		'#type' => 'checkboxes',
		'#title' => t('User is member of'),
		'#default_value' => $portal_ismember,
		'#options' => $portal_formatted
	);
?>

(Drupal 6)

www.netnode.ch

Heine’s picture

Checkboxes #options are HTML. Node titles are plaintext. You need to check_plain the node title ($portal_formatted[$node->nid] = check_plain($node->title);) to ensure the title is displayed properly and doesn't open an XSS hole.

Rene Hostettler’s picture

Need to set the default options on some checkboxes on a custom form for a custom view/search where the form is submitted to self and no $form_state values saved to db was a massive headache. Can't believe there is no drupal function for this. I wrote this one hopefully its useful for someone

 function set_default_checkboxes($element_name, $form_state, &$form) {
   $form[$element_name]['#default_value'] = array();
   if (is_array($form_state['values'][$element_name])) {
	foreach ($form_state['values'][$element_name] as $default_value) {
     $form[$element_name]['#default_value'][] = $default_value;
	}
	}
	
 }

// To set default options replace YOUR_CHECKBOXES_NAME with your checkboxes form element name
// You no longer have to set the #default_value in your form element as its set to an empty array inside the function
set_default_checkboxes($element_name='YOUR_CHECKBOXES_NAME', $form_state, &$form);
NickAT’s picture

Thanks Mbug for this function, it really helped me out with some forms issues that were wracking my brain.

Setting a default value for checkboxes honestly should be in the core code, I shouldn't have to theme my form so that my values get initialized, it should be a standard coding practice.

Anyway, thanks again mbug
Nick

cardiffmike’s picture

I couldn't find documentation anywhere on how to set the default values for a group of checkboxes, and after much trial and error, this is what I found that works for me (Drupal 7)

Checkboxes with four items, with simple boolean values to be pre-selected when showing form:

'#default_value' => array(0 => ($item1 == 1 ? 0 : null), 1 => ($item2 == 1 ? 1 : null), 2 => ($item3 == 1 ? 2 : null), 3 => ($item4 == 1 ? 3 : null) ),

The number corresponds to the order of the checkboxes, starting from zero - so rather than listing each checkbox in the default values array and their state (selected or not selected), the default values array only holds the instance number of each checkbox that should be selected.

chera.jaswinder’s picture

I am new bee to this Drupal still learning...........

Set the #value of checkboxes which will help you to check the checkboxes. Send an array to set multiple values at once.

exploring makes u learn faster.............learning little slower......

ElusiveMind’s picture

Do not set #value... not unless you don't want people to be able to change the state of their checkboxes within a form. Use #default_value to set the current state and it will update with the state when the form is saved.

MaximusOfLondon’s picture

If you want to select options based on indexes you need to provide '#default_value' array where keys and values are equal to indexes you want to select.
This works for me in Drupal 7 in hook_form:

$options = array(1 => 'one', 2 => 'two', 3 => 'three');
$indexes = array(1, 3);
$indexes = array_combine($indexes, $indexes);

$form['checks'] = array(
  '#type' => 'chekboxes',
  '#options' => $options, 
  '#default_value' = $indexex;
);

Hope this helps.

DeeZone’s picture

While very helpful, note that there's typos in MaximusOfLondon's example code.

'#type' => 'chekboxes',
should be:
'#type' => 'checkboxes',

and

'#default_value' = $indexex;
should be:
'#default_value' => $indexes;

Frederic wbase’s picture

Hello

i did it with a form_alter on the user registration form like this:

$form['account']['roles']['4']['#type'] = 'checkbox';
$form['account']['roles']['4']['#title'] = 'promotor';
$form['account']['roles']['4']['#default_value'] = TRUE;

http://www.wbase.be twitter: @wbase_be

anou’s picture

And not to mention that

$indexes = array_combine($indexes, $indexes);

should be

$indexes = array_combine($indexes, $options);

David THOMAS
http://www.smol.org

varghese’s picture

'#type' => 'checkbox', change to checkboxes

darquesp’s picture

I'm using drupal 7
Using the array_combine did not work but after deleting that line ($indexes = array_combine($indexes, $indexes);) it worked perfectly .
Thanks a lot for the post , saved me a lot of time.

valthebald’s picture

You can use #value_callback if you want your checkbox to return values in both checked and unchecked states

jeepster’s picture

Hi,

I have done a module to create a new Pre-built option list for a webform field:

// Basically says to add Services to the "Load a pre-built option list" list.
$items['services'] = array(
'title' => t('Services'),
'options callback' => 'webform_preloadServices_options_services',
'default_value' => array(0,2),
);

The module is working and I can see the options that I need but I can't set a default option.

Can anybody tell me what am I doing wrong? Is it possible to set a default option? It could be related with #value_callback, and how to use it??

Thanks a lot!!!

cesar ll’s picture

$options = array('1'=>'one','2'=>'two','3'=>'tree');
$form['modules_active'] = array(
'#type' => 'checkboxes',
'#title' => t('Modules Active'),
'#options' => $options,
'#default_value' => variable_get('modules_active', array()),
);

//$values = array_filter(variable_get('modules_active', array()));
//print_r($values);