Commit d8e43b7c by Alexander Makarov

Minor fixed for file upload guide

parent 0fd0f430
...@@ -51,14 +51,15 @@ Next, create a view that will render the form: ...@@ -51,14 +51,15 @@ Next, create a view that will render the form:
```php ```php
<?php <?php
use yii\widgets\ActiveForm; use yii\widgets\ActiveForm;
?>
$form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?> <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
<?= $form->field($model, 'file')->fileInput() ?> <?= $form->field($model, 'file')->fileInput() ?>
<button>Submit</button> <button>Submit</button>
<?php ActiveForm::end(); ?> <?php ActiveForm::end() ?>
``` ```
The `'enctype' => 'multipart/form-data'` is necessary because it allows file uploads. `fileInput()` represents a form The `'enctype' => 'multipart/form-data'` is necessary because it allows file uploads. `fileInput()` represents a form
...@@ -86,7 +87,7 @@ class SiteController extends Controller ...@@ -86,7 +87,7 @@ class SiteController extends Controller
if (Yii::$app->request->isPost) { if (Yii::$app->request->isPost) {
$model->file = UploadedFile::getInstance($model, 'file'); $model->file = UploadedFile::getInstance($model, 'file');
if ($model->validate()) { if ($model->file && $model->validate()) {
$model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension); $model->file->saveAs('uploads/' . $model->file->baseName . '.' . $model->file->extension);
} }
} }
...@@ -162,7 +163,29 @@ received a valid image that can be then either saved or processed using the [Ima ...@@ -162,7 +163,29 @@ received a valid image that can be then either saved or processed using the [Ima
### Uploading multiple files ### Uploading multiple files
If you need to download multiple files at once, some adjustments are required. If you need to download multiple files at once, some adjustments are required.
Model:
```php
class UploadForm extends Model
{
/**
* @var UploadedFile|Null file attribute
*/
public $file;
/**
* @return array the validation rules.
*/
public function rules()
{
return [
[['file'], 'file', 'maxFiles' => 10], // <--- here!
];
}
}
```
View: View:
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment