Andhika R.K.
Andhika R.K.

Reputation: 436

Codeigniter - Edit Form with Checkbox

I'm using codeigniter and have a problem with my edit form in checkbox. The checkbox have 2 values 1 and 0, if checked then the value is 1 and if unchecked then the value is 0.

here is my controller:

function updatepost($id=0){
    $data = $_POST;
    $this->db->where('id_post',$id);
    $outp = $this->db->update('post',$data);
}

And here is my view

sport <input type="checkbox" name="sport" value="1" <?php if($data['sport'] == '1'){echo 'checked';}?> />

tekno <input type="checkbox" name="tekno" value="1" <?php if($data['tekno'] == '1'){echo 'checked';}?>/>

game <input type="checkbox" name="game" value="1" <?php if($data['game'] == '1'){echo 'checked';}?>/>

if i unchecked the checkbox, value should be '0';

My question is how to get value if the checkbox is uncheked?

Many thanks for the answer..

Upvotes: 1

Views: 4896

Answers (2)

radiopassive
radiopassive

Reputation: 566

In your controller file replace the $data = $_POST; line by the following code

$data['sport']  = (array_key_exists('sport',$_POST)) ? $_POST['sport'] : 0;
$data['tekno']  = (array_key_exists('tekno',$_POST)) ? $_POST['tekno'] : 0;
$data['game']   = (array_key_exists('game',$_POST)) ? $_POST['game'] : 0;

Upvotes: 0

Pupil
Pupil

Reputation: 23958

Checkboxes are posted only if they are checked.

In your controller, check if they are posted,

if posted, value is 1 else 0.

Example Code:

$sport = 0;
if (! empty($_POST['sport']) {
  $sport = 1;
}

If you want to use ternary operators, use:

$sport = (! empty($_POST['sport']) ? 1 : 0;

So, final code:

function updatepost($id=0){
  // Assign default values in view that they are not getting
  // posted if they are not checked.
  // If they are posted, they will be overriden in $data.
  $data['sport'] = $data['tekno'] = $data['tekno'] = 0;
  $data = $_POST;
  $this->db->where('id_post',$id);
  $outp = $this->db->update('post',$data);
}

Upvotes: 1

Related Questions