如何在表单中的字段级别或模型中的验证规则中添加条件,使该字段在 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'],
在 Controller 的更新操作中我添加了:
$model->scenario = 'update';
但是上面的代码使更新场景中需要字段,我希望这些字段在创建操作中保持隐藏状态并仅在更新时显示。
更新 表单.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)您可以为表单呈现不同的 View 。
创建
View :
$this->render('_create-form', ['model' => $model];
更新
View :
$this->render('_update-form', ['model' => $model];
2) 如果您只想使用一种表单并防止代码重复,您可以添加对所需操作的检查:
表单
View :
use Yii;
...
if ($this->context->action->id == 'update') {
echo $form->field($model, 'discharged')->checkBox();
}
用于评论中建议的验证使用场景。
关于javascript - yii2:根据操作有条件显示/显示字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28766631/