Forms 使用单一表单创建和更新时,如何在yii中默认选中复选框

Forms 使用单一表单创建和更新时,如何在yii中默认选中复选框,forms,yii,Forms,Yii,我正在使用单一表单创建和更新表单。我需要在以下表单中默认选中复选框 <div class="row" style='float:left;;margin-left:5px'> <?php echo '<span for="label" style="margin-bottom:5px;font-size: 0.9em;font-weight: bold;">Label</span><br />'; ?>

我正在使用单一表单创建和更新表单。我需要在以下表单中默认选中复选框

<div class="row" style='float:left;;margin-left:5px'>
        <?php echo '<span for="label" style="margin-bottom:5px;font-size: 0.9em;font-weight: bold;">Label</span><br />'; ?>
        <?php echo $form->checkBox($model,'label_name',array('value'=>1,'uncheckValue'=>0,'checked'=>'checked','style'=>'margin-top:7px;')); ?>
        <?php echo $form->error($model,'label_name'); ?>
    </div>


我使用上面的代码来达到同样的目的,我没有得到预期的结果。更新表单时,即使未选中,也会显示选中状态

您的要求是在创建和更新时保持选中复选框。checked=checked将用于创建表单,但在更新时,您必须通过代码处理它

我得到了解决方案,我使用了代码本身,请查看

<div class="row" style='float:left;;margin-left:5px'>
        <?php echo '<span for="label" style="margin-bottom:5px;font-size: 0.9em;font-weight: bold;">Label</span><br />'; ?>
        <?php echo $form->checkBox($model,'label_name',array('value'=>1,'uncheckValue'=>0,'checked'=>($model->id=="")?true:$model->label_name),'style'=>'margin-top:7px;')); ?>
        <?php echo $form->error($model,'label_name'); ?>
    </div


更好的解决方案是在控制器中设置值:

public function actionCreate() {
    $model = new ModelName();

    if (isset($_POST[$model])) {
        // ... save code here
    }
    else {
        // checkboxes for label 'label_name' with value '1' 
        //   will be checked by default on first load
        $model->label_name = true; // or 1
    }

    $this->render('create', array(
        'model' => $model,
    ));
}
或者更好,在模型中的
afterConstruct()
函数中:

protected function afterConstruct() {

    parent::afterConstruct();

    $this->label_name = true; // or 1
}
public $label_name = true;

您只需在模型中设置默认值:

protected function afterConstruct() {

    parent::afterConstruct();

    $this->label_name = true; // or 1
}
public $label_name = true;
请点击下面的链接


我希望该链接有用。

您指定的链接会打开“未找到页面”错误。请从重定向的URL中删除.html