Skip to content

Instantly share code, notes, and snippets.

@mikedfunk
Created November 2, 2012 23:22
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mikedfunk/4004986 to your computer and use it in GitHub Desktop.
CodeIgniter Checkbox Helper

Checkbox Helper

Just a tiny helper to help with checkboxes. When you uncheck a checkbox, it's value does not get sent in the form values. Instead of telling CodeIgniter you want to set this value to 0, it says "don't change it." This fixes that, one by one, by setting the value of the associated $_POST array item to zero. You can also pass in an array of checkbox names and it will do each one.

Usage

$this->load->helper('checkbox');

// set post values to zero for unchecked boxes
fix_unchecked(['is_active', 'is_enabled', 'is_verified']);
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* @author Mike Funk
* @link http://mikefunk.com
* @email mike@mikefunk.com
* @file checkbox.php
*/
/**
* checkbox value fixer. If a checkbox is not checked, sets it's value
* to zero.
* @param mixed $name the checkbox form field name. Can be passed as a
* string or as an array.
* @return void
*/
function fix_unchecked($name)
{
if (!is_array($name)) {$name = array($name);}
foreach ($name as $item)
{
if (!$this->input->post($item)) {$_POST[$item] = 0;}
}
}
/* End of file checkbox.php */
/* Location: ./application/helpers/checkbox.php */
@pporlan
Copy link

pporlan commented Jan 8, 2014

Hi!!
Nice and useful snippet, I have modified it to use $CI instead of $this, and also check if there has been a POST request.

https://gist.github.com/pporlan/8316087

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment