2019独角兽企业重金招聘Python工程师标准>>>
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:
'create-from','layout'=>'horizontal', //据查unique验证必须开这个'enableAjaxValidation' => true]);?>errorSummary($model); ?>