在Codeigniter中设置单选按钮的值

时间:2014-04-01 11:04:59

标签: php codeigniter radio-button

在我的编辑细节表单中,我有一个值为01的单选按钮。我想要的是,在加载表单时,即当用户点击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');  

任何人都可以帮我解决这个问题吗?提前谢谢。

5 个答案:

答案 0 :(得分:6)

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函数

答案 1 :(得分:0)

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

答案 2 :(得分:0)

检查以下默认值检查

<?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'); ?>

答案 3 :(得分:0)

您可以使用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,也适用于其他版本。

答案 4 :(得分:0)

使用codeignitor表单功能:

<?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')); ?>&nbsp;&nbsp;
<?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'); ?>