Yii2 Extension to upload models attachment into Flysystem (S3)
Upload models attachment to Flysystem
You can see the demo of upload input on the krajee website
install yii2-flysystem and filesystem of your choice.
Please look closely at its documentation for installation. (it may get some update)
The preferred way to install this extension is through composer.
Either run
php composer.phar require fredyns/yii2-attachments "dev-master"
or add
"fredyns/yii2-attachments": "dev-master"
to the require section of your composer.json
file.
Add module to common/config/main.php
(advanced template)
for basic app you should add to both config/web.php
& config/console.php
.
'modules' => [
...
'attachments' => [
'class' => fredyns\attachments\Module::class,
'rules' => [ // Rules according to the FileValidator
'maxFiles' => 10, // Allow to upload maximum 3 files, default to 3
'mimeTypes' => 'image/png', // Only png images
'maxSize' => 1024 * 1024 // 1 MB
],
'tableName' => '{{%attachments}}' // Optional, default to 'attach_file'
'filesystem' => 'awss3Fs' // you can change though
]
...
]
Apply migrations
```php
'controllerMap' => [
...
'migrate' => [
'class' => 'yii\console\controllers\MigrateController',
'migrationNamespaces' => [
'fredyns\attachments\migrations',
],
],
...
],
```
```
php yii migrate/up
```
Attach behavior to your model (be sure that your model has “id” property)
public function behaviors()
{
return [
...
'fileBehavior' => [
'class' => \fredyns\attachments\behaviors\FileBehavior::class,
]
...
];
}
Make sure that you have added 'enctype' => 'multipart/form-data'
to the ActiveForm options
Make sure that you specified maxFiles
in module rules and maxFileCount
on AttachmentsInput
to the number that you want
In the form.php
of your model add file input
<?= \fredyns\attachments\components\AttachmentsInput::widget([
'id' => 'file-input', // Optional
'model' => $model,
'options' => [ // Options of the Kartik's FileInput widget
'multiple' => true, // If you want to allow multiple upload, default to false
],
'pluginOptions' => [ // Plugin options of the Kartik's FileInput widget
'maxFileCount' => 10 // Client max files
]
]) ?>
Use widget to show all attachments of the model in the view.php
<?= \fredyns\attachments\components\AttachmentsTable::widget([
'model' => $model,
'showDeleteButton' => false, // Optional. Default value is true
])?>
You can get all attached files by calling $model->files
, for example:
foreach ($model->files as $file) {
echo $file->path;
}
You may add the following function to your model
public function init(){
$this->on(\fredyns\attachments\behaviors\FileBehavior::EVENT_AFTER_ATTACH_FILES, function ($event) {
/** @var $files \fredyns\attachments\models\File[] */
$files = $event->files;
//your custom code
});
parent::init();
}