當unique驗證運到圖片上傳時

model:php

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:ajax

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:app

<?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]) ?>
相關文章
相關標籤/搜索