I had an issue when edit checkbox. Checkbox not cheked when edit. I'm using codeigniter.
This is my model:
public function categories_post($id)
{
$this->db->select('categories.idcategory, categories.category_name');
$this->db->from('categories');
$this->db->join('categories_detail', 'categories_detail.idcategory = categories.idcategory', 'inner');
$this->db->join('posts', 'posts.idpost = categories_detail.idpost', 'inner');
$this->db->where('posts.idpost', $id);
return $this->db->get();
}
This my controller:
public function edit($id='')
{
$data['post'] = $this->posts->getpostbyid('posts',$id);
$data['a'] = $this->posts->categories_post($id)->row_array();
$data['tags'] = $this->posts->tags_post($id);
$data['media'] = $this->datamedia->list_image();
$data['title']="Edit Pos";
$data['file']="posts/editpost";
$data['categories'] = $this->posts->getallcategories('categories');
$this->load->view('form_template',$data);
}
View :
<?php
foreach ($categories as $data) { ?>
<div class="form-group">
<input <?php if($a['idcategory']){ echo 'checked'; } ?> type="checkbox" name="category[]" value="<?php echo $data->idcategory ?>"> <?php echo $data->category_name ?>
</div>
<?php } ?>
How can i make it checked ?
enter image description here enter image description here
i just updated my qustion. it always showing just 1 checked box althought i have more categories. (sorry my english not good)
Try to change the checkbox input to :
<input <?php echo $data->idcategory == $a['idcategory'] ? 'checked' : '' ?> type="checkbox" name="category[]" value="<?php echo $data->idcategory ?>"> <?php echo $data->category_name ?>
Solved. I just add foreach inside input tag in my view
<?php
foreach ($categories as $data) { ?>
<div class="form-group">
<input <?php foreach ($a as $aa) { echo $data->idcategory == $aa['idcategory'] ? 'checked' : ''; } ?> type="checkbox" name="category[]" value="<?php echo $data->idcategory ?>"> <?php echo $data->category_name ?>
</div>
<?php } ?>