Uploading files in Yii is done via the a form model, its validation rules and some controller code. Let's review what's
Uploading files in Yii is done via a form model, its validation rules and some controller code. Let's review what's
required to handle uploads properly.
...
...
@@ -39,7 +39,7 @@ class UploadForm extends Model
}
```
In the code above, we've created a model `UploadForm` with an attribute `$file` that will become `<input type="file">` in
In the code above, we've created a model `UploadForm` with an attribute `file` that will become `<input type="file">` in
the HTML form. The attribute has the validation rule named `file` that uses [[yii\validators\FileValidator|FileValidator]].
### Form view
...
...
@@ -65,7 +65,7 @@ input field.
### Controller
Now create the controller that connects the form and model together:
Now create the controller that connects the form and the model together:
```php
namespaceapp\controllers;
...
...
@@ -95,13 +95,16 @@ class SiteController extends Controller
```
Instead of `model->load(...)`, we are using `UploadedFile::getInstance(...)`. [[\yii\web\UploadedFile|UploadedFile]]
does not run the model validation, rather it only provides information about the uploaded file. Therefore, you need to run the validation manually via `$model->validate()` to trigger the [[yii\validators\FileValidator|FileValidator]] that expects a file:
does not run the model validation, rather it only provides information about the uploaded file. Therefore, you need to run the validation manually via `$model->validate()` to trigger the [[yii\validators\FileValidator|FileValidator]]. The validator expects that
the attribute is an uploaded file, as you see in the core framework code:
```php
$fileinstanceofUploadedFile||$file->error==UPLOAD_ERR_NO_FILE//in the code framework