yii2:依赖于Action的条件显示/显示字段


yii2:Conditional dispaly/show field dependent on Action

如何在表单中的字段级别或模型中的验证规则添加条件,使字段在action/create上保持隐藏状态,仅在action/update上显示。

例如,我有一个字段,我只想在更新屏幕上显示,而不想在创建屏幕上显示。

$form->field($model, 'discharged')->checkBox();

好的,我已经按照评论中的建议更新了代码,比如模型

public function scenarios()
    {
        $scenarios = parent::scenarios();
        $scenarios['update'] = ['discharged', 'discharge_date'];
        return $scenarios;
    }

然后在规则中

[['discharged', 'discharge_date'], 'required', 'on' => 'update'],

在我在控制器中的更新操作中,我添加了:

$model->scenario = 'update';

但上面的代码使字段在更新场景中是必需的,我希望这些字段在创建操作中保持隐藏状态,只在更新时显示。

更新form.php

<?php 
    echo Tabs::widget([
    'items' => [
     .....
    '<div class="col-lg-6">'.
                if(Yii::$app->controller->action->id == 'update') {
                $form->field($model, 'discharged')->checkBox()
                }
                        .'</div>'.

我不知道该如何在更新屏幕中显示字段。谢谢

1)您可以为表单呈现不同的视图。

create视图:

$this->render('_create-form', ['model' => $model];

update视图:

$this->render('_update-form', ['model' => $model];

2)如果您只想使用一个表单并防止代码重复,您可以添加所需操作的检查:

form视图:

use Yii;
...
if ($this->context->action->id == 'update') {
    echo $form->field($model, 'discharged')->checkBox();
}

对于注释中建议的验证使用场景。