unique 验证与图片的 require 验证无法共赢,大家看看 [ 2.0 版本 ]
model:
public $imageFile;
public function rules()
{
return [
[['name','cat','SKU','imageFile'], 'required'],
[['cat','name', 'photo', 'SKU',], 'string', 'max' => 100],
['photo','safe','on'=>'update'],
['SKU', 'unique', 'message' => '产品编码已存在.'],
['imageFile', 'image', 'extensions' => 'png, jpg',
'minWidth' => 100, 'maxWidth' => 1500,
'minHeight' => 100, 'maxHeight' => 1000,
],
];
}
controller:
public function actionCreate() {
$model = new Product();
//unique的ajax验证
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
if ($model->load(Yii::$app->request->post()) ) {
$model->imageFile = UploadedFile::getInstance($model, 'imageFile');
$filename = '/uploads/product/' . time() . uniqid() . '.' . $model->imageFile->extension;
$path = Yii::$app->basePath . $filename;
$model->photo = $filename;
//$model->validate();
if ( $model->save()) {
$model->imageFile->saveAs($path);
return $this->redirect(['view', 'id' => $model->id]);
}else{
return $this->render('create', [
'model' => $model,
]);
}
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
view:
.....
<?php $form = ActiveForm::begin(['id'=>'create-from',
'layout'=>'horizontal',
//据查unique验证必须开这个
'enableAjaxValidation' => true]);
?>
<?php echo $form->errorSummary($model); ?>
<div class="form-group">
<?php echo Html::submitButton('新建产品', ['class' => 'btn btn-lg btn-success']) ?>
</div>
<?php echo $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<?php echo $form->field($model, 'cat')->dropDownList( yii\helpers\ArrayHelper::map(\common\models\ArticleCategory::findBySql('select title from article_category')->all(), 'title', 'title'), ['prompt' => '---请选择---']) ?>
<?php //echo $form->field($model, 'cat')->textInput(['maxlength' => true]) ?>
<?php echo $form->field($model, 'imageFile')->fileinput(['maxlength' => true]) ?>
......
搞搞的传奇 补充于 2017-06-17 23:35
页面端unique验证正常,但是图片的require验证一直显示,不能为空,明明已经选择了文件
参考了这个
https://stackoverflow.com/questions/33076125/how-to-use-unique-rules-in-active-record-yii2
搞搞的传奇 补充于 2017-06-18 09:12
问题解决
//unique的ajax验证
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
$model->imageFile = 'test';//伪造图片一个数据,这样ajax验证通过
return ActiveForm::validate($model);
}
共 3 个回答
搞搞的传奇
注册时间:2015-02-24
最后登录:2020-06-04
在线时长:24小时46分
最后登录:2020-06-04
在线时长:24小时46分
- 粉丝8
- 金钱5
- 威望10
- 积分345