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;
$model->imageFile = 'test';//伪造图片一个数据,这样ajax验证通过
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]) ?>