Community

Persistent checkbox cannot alter using hook_form_alter

I'm trying to alter a checked checkbox using hook_form_alter with this:

$form['foo']['#attributes'] = array();

and/or
$form['foo']['#default_value'] = '0';

Basically the current output of the form is this:

[foo] => array (
       [#type] => [checkbox]
       [#attributes] => array (
           [checked] => [checked]
       )
)

This is a checkbox that is checked by default. Now I want to uncheck the box and save it as that.

I managed to uncheck the box by default but that value does not save at all. Form is still being submitted with the checkbox checked.

What am I missing?

Comments

#default_value is the correct

#default_value is the correct array entry to change. There's a couple of other considerations, though: is this field getting its setting from somewhere else? In other words, is the form being filled in from a store such as the database? If so, then the default will presumably be overridden by the actual current value. Another possibility is browser caching of form data. Sometimes the browser will prefill values and (temporarily) ignore what's in the HTML.

Also, is it possible the field is created/altered by another module? It may be that your altering happens too early and that some other code sets the value. You might try using the alter hook to add a #after_build callback in which you unset the default value.

nobody click here