0

I currently update my database records with an input like this

$this->my_model->update($id, $this->input->post()));

(This is after I have performed a validation on all the input. The "model" also has a white_list of data to expect.)

Problem: if I am updating a checkbox, and it is "unticked" (i.e. 'false') - then that field is not 'posted' by the browser.

For example - if I tick checkbox_two - but leave checkbox_one unticked, $_POST shows:

[field_one] = "some value"
[field_two] = "some value"
[checkbox_two] = 1

Therefore my model will not update that field - since it is not part of the post.

The same does not happen in reverse - because a "ticked" checkbox is posted as "1" - and thus is correctly updated.

[field_one] = "some value"
[field_two] = "some value"
[checkbox_one] = 1
[checkbox_two] = 1

Question: Does anyone have an elegant solution to handle this, other than having to always specifically check for each checkbox?

Laurence
  • 58,936
  • 21
  • 171
  • 212
  • This seems a decent solution, the one about using hidden form elements. http://stackoverflow.com/questions/1809494/post-the-checkboxes-that-are-unchecked – Rick Calder Nov 20 '12 at 11:22
  • You can do a `$update['field'] = $this->input->post('checkbox') ? 1 : 0;` This assumes that you always have the checkbox in your form. – Silviu G Nov 20 '12 at 11:27

1 Answers1

3
<input type="hidden" name="example" value="FALSE" />
<input type="checkbox" name="example" value="TRUE" />

This practice is easy and logical. If checkbox is checked, $this->input->post('example') == 'TRUE' else, $this->input->post('example') == 'FALSE'.

The latest given value of a name="" overrides previous, thus givin prio checkbox > hidden.

EDIT: this solution is equal to given most rated answer in Rick Calder's comment. I've also come to this conclusion on my own, though.

Robin Castlin
  • 10,956
  • 1
  • 28
  • 44