PHPackages                             floor12/yii2-module-files - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [File &amp; Storage](/categories/file-storage)
4. /
5. floor12/yii2-module-files

ActiveYii2-extension[File &amp; Storage](/categories/file-storage)

floor12/yii2-module-files
=========================

Yii2 module to upload and manage files to your models.

1.6.2(1y ago)1612.4k20[3 issues](https://github.com/floor12/yii2-module-files/issues)6MITPHPPHP &gt;=7.3

Since Jun 30Pushed 1y ago1 watchersCompare

[ Source](https://github.com/floor12/yii2-module-files)[ Packagist](https://packagist.org/packages/floor12/yii2-module-files)[ RSS](/packages/floor12-yii2-module-files/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (5)Dependencies (8)Versions (64)Used By (6)

yii2-module-files
=================

[](#yii2-module-files)

[![Scrutinizer Code Quality](https://camo.githubusercontent.com/e5dd27756e29eadea3039f9e3997240058f86a1dac8637a149b30d4456602563/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f666c6f6f7231322f796969322d6d6f64756c652d66696c65732f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/floor12/yii2-module-files/?branch=master)[![Latest Stable Version](https://camo.githubusercontent.com/ae352ff8ba6f5a5c5547208c18d6d6e8beee00d21056d353793b973afceb9024/68747470733a2f2f706f7365722e707567782e6f72672f666c6f6f7231322f796969322d6d6f64756c652d66696c65732f762f737461626c65)](https://packagist.org/packages/floor12/yii2-module-files)[![Latest Unstable Version](https://camo.githubusercontent.com/e1f78b92987e0e98e93da4d0b1f04edbc11b6af8e76deb9e93bd8de8006993bc/68747470733a2f2f706f7365722e707567782e6f72672f666c6f6f7231322f796969322d6d6f64756c652d66696c65732f762f756e737461626c65)](https://packagist.org/packages/floor12/yii2-module-files)[![Total Downloads](https://camo.githubusercontent.com/da24a564454e70d427a974872d6a8f6aab2ba40e48cd63a4bf8f3285b5a6216a/68747470733a2f2f706f7365722e707567782e6f72672f666c6f6f7231322f796969322d6d6f64756c652d66696c65732f646f776e6c6f616473)](https://packagist.org/packages/floor12/yii2-module-files)[![License](https://camo.githubusercontent.com/7d8dd67776977402cbf9930d048c6e6bdb0ee19d5f7e97f549387c62bad16f04/68747470733a2f2f706f7365722e707567782e6f72672f666c6f6f7231322f796969322d6d6f64756c652d66696c65732f6c6963656e7365)](https://packagist.org/packages/floor12/yii2-module-files)

*Этот файл доступен на [русском языке](README_RU.md).*

About the module
----------------

[](#about-the-module)

[![FileInputWidget](https://camo.githubusercontent.com/204ac19df3bacbb6279eee2a7f6ea30f6add15344853ef6e4715e8649bbe1418/68747470733a2f2f666c6f6f7231322e6e65742f66696c65732f64656661756c742f6765743f686173683d3761643162396465653130626237636235626437336431633837343732346531)](https://camo.githubusercontent.com/204ac19df3bacbb6279eee2a7f6ea30f6add15344853ef6e4715e8649bbe1418/68747470733a2f2f666c6f6f7231322e6e65742f66696c65732f64656661756c742f6765743f686173683d3761643162396465653130626237636235626437336431633837343732346531)

This module was designed to solve the problem of creating file fields in ActiveRecord models of the Yii2 framework. The main components of the module are:

- `floor12\files\components\FileBehaviour` - behavior that must be connected to the ActiveRecord model;
- `floor12\files\components\FileInputWidget` - an InputWidget that allows you to add, edit and generally work with files;
- `floor12\files\components\FileListWidget` - an additional widget to display a list of files with the abilities to view images in the Lightbox2 gallery, download all files of the current field in zip format, and view the Word and Excel files using the Microsoft office online.

### Key features

[](#key-features)

- adding one or more fields with files to the ActiveRecord model;
- setting up validation of these fields using the standard `FileValidator` defined in the` rules ()`section;
- in the case of working with images - the ability to configure the image ratio (in this case, when loading an image through the `FileInputWidget` widget will automatically open a modal window to crop the image with the desired ratio);
- thumbnails creating with optimal sizes for each case in site template. Also, these thumbnails supports WEBP format;
- download files in ZIP-format
- `FileInputWidget` supports changing of files order by drag-and-drop, cropping and filename updating;
- in case of drag-and-drop uploading, the file result file order is the same as on client folder;
- automatic horizon detection by EXIF ​​tag;
- if you need to add images to the model not with the web interface of the site, but using console parsers and other similar cases - its possible. For this case, the module includes two classes: `FileCreateFromInstance`and` FileCreateFromPath` with helps add files to AR model from server file system;
- in case of video files: recoding them to h264 using the ffmpeg utility;

### i18n

[](#i18n)

At this stage, the module supports the following languages:

- English
- Russian

### Principle of operation

[](#principle-of-operation)

All files data is stored in the `file` table. The `file` model relay to the model by three fields:

- `class` - the full class name of the relay model
- `field` - the name of the model field
- `object_id` - primary key of the model

When file added to the form, it uploads to server in background where all processing takes place. As a result of this processing, it is written to disk and a new entry is created for it in the `file` table, with the fields` class` and `field` filled with data from the model, and` object_id` is empty and will assign only after saving the ActiveRecord model. When a file is deleted from the widget, it is not deleted from the disk and the `file` table, just `obejct_id`equals to 0. You can use the console command` files / console / clean` to periodically clean up this kind of orphan files.

Install and setup
-----------------

[](#install-and-setup)

To add this module to your app, just run:

```
$ composer require floor12/yii2-module-files
```

or add this to the `require` section of your composer.json.

```
"floor12/yii2-module-files": "dev-master"
```

Then execute a migration to create `file` table.

```
$ ./yii migrate --migrationPath=@vendor/floor12/yii2-module-files/src/migrations/
```

After that, include module data in `modules` section of application config:

```
'modules' => [
            'files' => [
                'class' => 'floor12\files\Module',
                'storage' => '@app/storage',
                'cache' => '@app/storage_cache',
                'token_salt' => 'some_random_salt',
            ],
        ],
    ...
```

Parameters to set:

- `storage` - the path alias to the folder to save files and image sources, by default it is located in the `storage`folder in the project root;
- `cache` - path alias to the folder of thumbnails of images that the module creates on the fly upon request and caches;
- `token_salt` - a unique salt to generate InputWidget tokens.

Usage
-----

[](#usage)

### Work with ActiveRecord Model

[](#work-with-activerecord-model)

To add one or more files fields to the ActiveRecord model, you need to connect `floor12\files\components\FileBehaviour`to it and pass list the field names that will store the files in the model. For example, for the User model, 2 file fields are defined here : `avatar` and` documents`:

```
 public function behaviors()
 {
     return [
         'files' => [
             'class' => 'floor12\files\components\FileBehaviour',
             'attributes' => [
                 'avatar',
                 'documents'
             ],
         ],
         ...
```

To have nice attribute labels in forms, add some labels to `attributeLabels()`:

```
 public function attributeLabels()
    {
        return [
            ...
            'avatar' => 'Аватар',
            'documents' => 'Документы',
            ...
        ];
    }
```

Setup validation rules in the `rules()` method of ActiveRecord model:

```
public function rules()
{
    return [
        // Avatar is required attribute
        ['avatar', 'required'],

        // Avatar allow to uploade 1 file with this extensions: jpg, png, jpeg, gif
        ['avatar', 'file', 'extensions' => ['jpg', 'png', 'jpeg', 'gif'], 'maxFiles' => 1],

        // Documens allows to upload a few files with this extensions: docx, xlsx
        ['documents', 'file', 'extensions' => ['docx', 'xlsx'], 'maxFiles' => 10],
    ...
```

### Work with files

[](#work-with-files)

If `maxFiles` in `FileValidator` equals to 1, this attribute will store an `floor12\files\models\File object`. Example:

```
// The href field contains web path to file source
echo Html::img($model->avatar->href)

// __toString() method of File object will return href as well
echo Html::img($model->avatar)
```

If the file is image, getPreviewWebPath method returns a web path to image thumbnail. By default thumbnail created with the jpeg or png format, it depends to source file. But also WEBP option is available.

`File::getPreviewWebPath(int $width = 0, int $height = 0 ,bool $webp = false)`

Usage example:

```
// User avatar thumbnail with 200px width
echo Html::img($model->avatar->getPreviewWebPath(200));

// User avatar thumbnail with 200px width  and WEBP format
echo Html::img($model->avatar->getPreviewWebPath(200, 0, true));

```

When `maxFiles` equals to 1, multiple upload is available. In this case, model field will contains an array if `floor12\files\models \File` objects:

```
foreach ($model->docs as $doc}
    Html::a($doc->title, $doc->href);
```

Here is another example, the advanced usage of thumbnails. In this case, we use modern `picture` and` source` tags, as well as media queries. As a result, we have 8 different thumbnails: 4 has webp format for those browsers that support this it, and 4 has jpeg format. Devices with retina displays will get an images with double resolution, regular screens have regular sized pictures. This example also uses different images widths at different screen widths (just as example of mobile/desktop image switching):

```
