yii2:Conditional dispaly/show 字段取决于操作
yii2:Conditional dispaly/show field dependent on Action
我如何在表单中的字段级别或模型中的验证规则中添加一个条件,该字段将在 action/create
上保持隐藏并仅在 action/update
上显示。
例如我有一个字段,我只想在更新屏幕而不是创建屏幕上显示。
$form->field($model, 'discharged')->checkBox();
好的,我已经按照 Model
中评论中的建议更新了代码
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();
}
对于评论中建议的验证使用场景。
我如何在表单中的字段级别或模型中的验证规则中添加一个条件,该字段将在 action/create
上保持隐藏并仅在 action/update
上显示。
例如我有一个字段,我只想在更新屏幕而不是创建屏幕上显示。
$form->field($model, 'discharged')->checkBox();
好的,我已经按照 Model
中评论中的建议更新了代码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();
}
对于评论中建议的验证使用场景。