如果很明显,我很抱歉。所以,我想不同的规则取决于用户选择的内容。我有一个更新表格:
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'news_title')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'news_content')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'check')->label('Picture update:')
->radioList(
[ 2 => 'Yes', 1 => 'No', 0 => 'Delete']) ?>
<?= $form->field($model, 'file')->fileInput() ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
并且只有当radioList的值为'2'时,我才想要fileInput。我的意思是如果用户选择1 =&gt; '不',或0 =&gt; '删除'fielInput可以为空。
public function rules() {
return [
[['news_content'], 'string'],
[['news_content'], 'required'],
[['created_at', 'updated_at'], 'safe'],
[['news_title', 'news_picture', 'created_by', 'updated_by'], 'string', 'max' => 255],
[['news_title'], 'required'],
[['news_picture'], 'required'],
[['file'], 'file', 'skipOnEmpty' => $this->checkRadio(), 'extensions' => 'png, jpg',],
[['check'], 'required', 'message' => 'Please ....'],
];
}
public function checkRadio() {
if ($this->check == 2) {
return false;
} else {
return true;
}
}
我试着在模型中编写一个函数,但是$ check变量总是有0值,我真的不明白为什么。 Yii2中有没有解决方案?
答案 0 :(得分:1)
这是documentation这是非常直接的,但这样的事情就足够了
[
'file', 'required',
'when' => function ($model) {
return $model->check == 2;
},
'whenClient' => "function (attribute, value) {
return $('#signupform-check-2').is(':checked');
}",
'message' => 'Please....'
]
只要启用了客户端验证,您就必须进行两次检查。后端和前端。
答案 1 :(得分:-1)
*********** Your Controller Like This ***********************
public function actionCreate(){
$model = new Model();
if(Yii::$app->request->post())
{
if($model->check ==2)
{
$model->scenario ='fileInputRequired';
}
else{
$model->scenario ='fileInputNotRequired';
}
}
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
********** Your Model Like This *****************
public function rules() {
return [
[['news_content','news_title','news_picture','check'], 'required'],
[['news_content'], 'string'],
[['created_at', 'updated_at'], 'safe'],
[['news_title', 'news_picture', 'created_by', 'updated_by'], 'string', 'max' => 255],
[['file'], 'file', 'on' =>'fileInputRequired', 'extensions' => 'png, jpg',],
];
}
function scenario()
{
return [
'fileInputRequired' => ['news_content', 'news_picture', 'news_title','file','check'];
'fileInputNotRequired' => ['news_content', 'news_picture','news_title','check'];
}