File Input Validation

In my Forms I have added, (the multi-form data option has been updated)


$form->field($model, 'image')->fileInput() 

In Model


[['image'],'file','types'=>'gif,png,jpg'],

And in controller


$model->categories_image = \yii\web\UploadedFile::getInstance($model,'image');

$model->categories_image->saveAs(\Yii::$app->basePath.'/web/'.$model->categories_image->name);



The problem is it uploads even though it is csv,doc or any other format.

Please let me know.

Thnx

Dinesh

the problem is you are getting the instance of uploaded file to your model’s property and you are saving instantly without validation so that all kind of files are saved. you should trigger validation by calling. $model->validate() method and if it is TRUE then you can save it

Thnx Ahamed,

But the problem is that it is not showing the error, Like : Type is wrong or Too large file.

have you validated your model previous getting the instance of the file uploaded. Please, show your full controller’s action.

Thnx Antonio,

Here is the code


if(isset($_FILES['Categories']) && $model->validate())

{

  $model->categories_image = \yii\web\UploadedFile::getInstance($model,'image');

}


if ($model->load($_POST) && $model->save()) {

$model->categories_image->saveAs(\Yii::$app->basePath.'/web'.$model->categories_image->name);                   

return $this->redirect(['view', 'id' => $model->categories_id]);

}       

How do I get the Model not to validate when there is no file upload. The $model->validate() fails if there is no upload.

Thnx

Dinesh

I got it !! :) Was using the old build. The latest build has a isEmpty Function in the File Validator.

Dinesh

Is your issue also solved?