代码点火器 - 使用复选框编辑表单


Codeigniter - Edit Form with Checkbox

我正在使用代码点火器,并且在复选框中的编辑表单有问题。该复选框有 2 个值 1 和 0,如果选中,则值为 1,如果未选中,则值为 0。

这是我的控制器:

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

这是我的观点

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';}?>/>

如果我取消选中该复选框,值应为"0";

我的问题是,如果复选框被取消选中,如何获得值?

非常感谢您的回答..

复选框仅在选中时才发布。

在您的控制器中,检查它们是否已发布,

如果发布,则值为 1 否则为 0。

示例代码:

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

如果要使用三元运算符,请使用:

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

所以,最终代码:

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);
}

在控制器文件中,将 $data = $_POST; 行替换为以下代码

$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;