在我的编辑详细信息表单中,我有一个单选按钮,其中包含值0
和1
。我想要的是,在加载表单时,即当用户单击edit
链接时,单选按钮应设置为数据库中的值。用户更改并提交表单后,它应保留提交的值。这怎么可能?
我尝试使用以下代码,但它不起作用。我知道不能这样做。 $row->videotype
具有来自数据库的值。
<input type="radio" name="trailer" value="1" <?php
if(set_radio('trailer', '1', TRUE)) {
echo set_radio('trailer', '1', TRUE);
} else {
if($row->videotype==1) ?> checked=checked <?php
} ?> />Yes
<input type="radio" name="trailer" value="0" <?php
if(set_radio('trailer', '0')) {
echo set_radio('trailer', '0');
} else {
if($row->videotype==0) ?> checked=checked <?php
} ?> />No
在表单提交功能(在控制器中)中,我已经为表单验证设置了这个:
$this->form_validation->set_rules('trailer', 'Trailer', 'is_numeric');
谁能帮我解决这个问题?提前谢谢。
set_value
函数在编辑表单验证中很有用,请尝试这种方式
<input type="radio" name="trailer" value="1" <?php
echo set_value('trailer', $row->videotype) == 1 ? "checked" : "";
?> />Yes
<input type="radio" name="trailer" value="0" <?php
echo set_value('trailer', $row->videotype) == 0 ? "checked" : "";
?> />No
在控制器中验证规则很好,如果帖子数据有空格,也请使用修剪规则
$this->form_validation->set_rules('trailer', 'Trailer', 'trim|is_numeric');
编辑:set_radio
功能在编辑模式下创建问题表单验证请使用set_value
功能
set_radio
是一个记录不佳的CI函数。你没有正确使用它。你最好不要使用它。这更简单:
<input type="radio" name="trailer" value="1" <?php if($row->videotype==1) ?> checked=checked <?php } ?> />Yes
<input type="radio" name="trailer" value="0" <?php if($row->videotype==0) ?> checked=checked <?php } ?> />No
使用codeignitor form函数:
<?php $selected = 'Yes'; ?>
<?php echo form_label('Trailer: ', 'trailer'); ?>
<?php echo form_label('Yes', 'trailer_yes') . form_radio(array('name' => 'trailer', 'value' => 'Yes', 'checked' => ('Yes' == $selected), 'id' => 'trailer_yes')); ?>
<?php echo form_label('No', 'trailer_no') . form_radio(array('name' => 'trailer', 'value' => 'No', 'checked' => ('No' == $selected), 'id' => 'trailer_no')); ?>
<?php echo form_error('trailer'); ?>
检查下面的默认值检查
<?php
echo $gender = $this->input->post('gender');
if($gender=='male' || empty($gender)) $mchecked=true;
else if($gender=='female') $fchecked=true;
?>
<?php echo form_label('Gender: ', 'gender'); ?><br />
<?php echo form_radio('gender', 'male', @$mchecked, 'id=male').form_label('Male', 'male'); ?>
<?php echo form_radio('gender', 'female', @$fchecked, 'id=female').form_label('Female','female'); ?>
您可以使用
form_validation库并以非常优雅的方式执行此操作。
您可以将form_radio()
与set_radio()
一起使用,如下所示:
$this->load->library('form_validation');
echo form_radio('trailer', '1', set_radio('trailer', '1', $row->videotype === "1" ? TRUE : FALSE));
echo form_radio('trailer', '0', set_radio('trailer', '0', $row->videotype === "0" ? TRUE : FALSE));
这在 PHP 5.6 上的 Codeigniter 3 上对我有用,在其他版本上也应该有效。