scribu/wp-scb-framework — Issue #6: Saving checkbox options
Author: relu
Created: 2011-11-10 17:53:26+00:00
State: open

Here's a problem I found while working with checkboxes. Let's say we have a AdminPage for a plugin to handle a true/false option that we want to toggle via a checkbox:

```php
array(
'title' => 'Do stuff',
'type' => 'checkbox',
'name' => 'dothat',
'desc' => ''
)
```

Now if I want to change that option to false I would normally have to uncheck the checkbox and submit, but the problem is that it won't save the new value! That's because when the checkbox is unchecked, on form submission there's no value sent, and therefore there's no key for that item in $_POST to check agains the defaults.

```php
$new_data = wp_array_slice_assoc( $_POST, array_keys( $this->options->get_defaults() ) );
// $_POST has no index 'dothat', so wp_array_slice_assoc won't return the value associated
// with it and and the option isn't updated.
```

What I've done to solve this problem was add:

```php
$checkboxes = array();

foreach ( (array) $this->options->get_defaults() as $key => $value ) {
if ( !array_key_exists($key, $_POST) )
$checkboxes[$key] = '';
}
```

right before

```php
$new_data = wp_array_slice_assoc( $_POST, array_keys( $this->options->get_defaults() ) );
```

then

```php
$new_data = array_merge($new_data, $checkboxes);
```

But this isn't a real solution not even close, because if we have more than one form on a page, the values that correspond to the other forms are unset on submit.

Another workaround that I thought of is to include an input type="hidden" with the same name as the checkbox or checkboxes group. That's a bit ugly... but it's sure better than the 1st for sure!
So we'll have:

```php
array(
'title' => 'Do stuff',
'type' => 'checkbox',
'name' => array('dothat', 'checkbox'),
'value' => 'the_value',
),

array(
'title' => '',
'type' => 'hidden',
'name' => array('dothat', 'hidden'),
'value' => 0,
)
```

What do you think can be done in this situation?