Francis
Francis

Reputation: 289

Uploading image and Validation in Yii2

I'm using Yii2 to create a simple uploading image and validate images extension. I've read in Yii2 docs and I don't know $model->validate() always return false. Any idea for me?

In my Model file, I set rules for imageFile:

public function rules()
    {
        return [
            [['name', 'price', 'description', 'image_path'], 'required'],
            [['price'], 'integer'],
            [['description'], 'string'],
            [['name', 'image_path'], 'string', 'max' => 255],
            [['imageFile'], 'image', 'skipOnEmpty' => false, 'extensions' => 'png, jpg, jpeg'],
        ];
    }

And in my action Index of Controller:

if ($model->load(Yii::$app->request->post())) {
    $model->imageFile = UploadedFile::getInstance($model, 'imageFile');
    if ($model->validate() && $model->save()) {
        $model->imageFile->saveAs('uploads/' . Yii::$app->params['bonuslyRewards'] . '/' . $model->imageFile->baseName . '.' . $model->imageFile->extension);
        $model->image_path = 'uploads/' . Yii::$app->params['bonuslyRewards'] . '/' . $model->imageFile->baseName . '.' . $model->imageFile->extension;
        return $this->redirect(['view', 'id' => $model->id]);
            }
    } else {
      return $this->render('create', [
            'model' => $model,
        ]);
    }

Upvotes: 3

Views: 5430

Answers (2)

Francis
Francis

Reputation: 289

I just remove image_path from the line:

[['name', 'price', 'description', 'image_path'], 'required'],

It's ok now.

Upvotes: 0

vishuB
vishuB

Reputation: 4261

change in your controller file like....

 if ($model->load(Yii::$app->request->post())) 
 {
   $model->imageFile = UploadedFile::getInstance($model, 'imageFile');          
   $path=Yii::getAlias('@webroot').'/your Path/';
   if(!empty($model->imageFile)){
        $model->imageFile->saveAs($path.$model->imageFile);
   }    
   if($model->save()){
      return $this->redirect(['view', 'id' => $model->id]);
   }
 }
 return $this->render('create', [
        'model' => $model,
    ]);
}

Upvotes: 1

Related Questions