tigrov / yii2-upload-behavior
File upload behavior for Yii2 ActiveRecord models
Installs: 2
Dependents: 0
Suggesters: 1
Security: 0
Stars: 0
Watchers: 3
Forks: 0
Open Issues: 0
Type:yii2-extension
Requires
- yiisoft/yii2: ~2.0.0
This package is auto-updated.
Last update: 2024-11-05 23:52:22 UTC
README
File upload behavior for Yii2 ActiveRecord models.
Installation
The preferred way to install this extension is through composer.
Either run
php composer.phar require --prefer-dist tigrov/yii2-upload-behavior
or add
"tigrov/yii2-upload-behavior": "~1.0"
to the require section of your composer.json
file.
Usage
Once the extension is installed, add the behavior to ActiveRecord model as follow:
Create a model with a file attribute
class Model extends \yii\db\ActiveRecord { /** * @inheritdoc */ public function behaviors() { return [ 'upload' => [ 'class' => '\tigrov\uploadBehavior\UploadBehavior', 'path' => '@runtime/upload', 'attributes' => ['file'], ], ]; } /** * @inheritdoc */ public function rules() { return [ [['file'], 'file', 'skipOnEmpty' => false], ]; } }
Create an action in a controller
class FormController extends \yii\web\Controller { public function actionUpload() { $model = new Model(); if ($model->load(\Yii::$app->request->post()) && $model->save()) { \Yii::$app->getSession()->setFlash('success', 'Model is saved.'); return $this->refresh(); } return $this->render('form', [ 'model' => $model, ]); } }
Create a form with the file attribute
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'file')->fileInput() ?>
<?= Html::submitButton('Submit') ?>
<?php $form::end(); ?>
After submitting the file it will be saved to specified path
.