{"issue":{"user":{"login":"relu","id":681456,"url":"https://api.github.com/users/relu","gravatar_id":"0002ac801d9f5c9d42a5ce1557c4c162","avatar_url":"https://secure.gravatar.com/avatar/0002ac801d9f5c9d42a5ce1557c4c162?d=https://a248.e.akamai.net/assets.github.com%2Fimages%2Fgravatars%2Fgravatar-140.png"},"title":"Saving checkbox options","milestone":null,"created_at":"2011-11-10T17:53:26Z","updated_at":"2011-12-15T23:42:12Z","labels":[],"state":"open","id":2200738,"html_url":"https://github.com/scribu/wp-scb-framework/issues/6","closed_at":null,"pull_request":{"patch_url":null,"html_url":null,"diff_url":null},"body":"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:\r\n\r\n```php\r\narray(\r\n\t'title' => 'Do stuff',\r\n\t'type' => 'checkbox',\r\n\t'name' => 'dothat',\r\n\t'desc' => ''\r\n)\r\n```\r\n\r\nNow 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.\r\n\r\n```php\r\n$new_data = wp_array_slice_assoc( $_POST, array_keys( $this->options->get_defaults() ) );\r\n// $_POST has no index 'dothat', so wp_array_slice_assoc won't return the value associated \r\n// with it and and the option isn't updated.\r\n```\r\n\r\nWhat I've done to solve this problem was add:\r\n\r\n```php\r\n$checkboxes = array();\r\n\t\t\r\nforeach ( (array) $this->options->get_defaults() as $key => $value ) {\r\n\tif ( !array_key_exists($key, $_POST) )\r\n\t\t$checkboxes[$key] = '';\r\n}\r\n```\r\n\r\nright before\r\n\r\n```php\r\n$new_data = wp_array_slice_assoc( $_POST, array_keys( $this->options->get_defaults() ) );\r\n```\r\n\r\nthen\r\n\r\n```php\r\n$new_data = array_merge($new_data, $checkboxes);\r\n```\r\n\r\nBut 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.\r\n\r\nAnother 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!\r\nSo we'll have:\r\n\r\n```php\r\narray(\r\n\t'title' => 'Do stuff',\r\n\t'type' => 'checkbox',\r\n\t'name' => array('dothat', 'checkbox'),\r\n\t'value' => 'the_value',\r\n),\r\n\r\narray(\r\n\t'title' => '',\r\n\t'type' => 'hidden',\r\n\t'name' => array('dothat', 'hidden'),\r\n\t'value' => 0,\r\n)\r\n```\r\n\r\nWhat do you think can be done in this situation?","number":6,"url":"https://api.github.com/repos/scribu/wp-scb-framework/issues/6","comments":5,"assignee":null},"action":"reopened"}