axelpal / yii2-attachments

文件上传和附加到模型扩展

安装: 683

依赖: 0

建议者: 0

安全: 0

星星: 0

关注者: 2

分支: 57

类型:yii2-extension

v1.0.1 2016-04-12 07:16 UTC

This package is auto-updated.

Last update: 2024-09-05 00:33:11 UTC


README

文件上传和附加到模型扩展

这个分支是由我和公司Elitmaster创建的。

演示

您可以在 krajee 网站上看到演示。

安装

  1. 安装此扩展的首选方式是通过 composer

    运行

    composer require axelpal/yii2-attachments "dev-master"
    

    或者

    "axelpal/yii2-attachments": "dev-master"
    

    将以下内容添加到您的 composer.json 文件的 require 部分。

  2. 将模块添加到您的主配置

    'aliases' => [
            '@file' => dirname(__DIR__),
        ],
        'modules' => [
            'file' => [
                'class' => 'file\FileModule',
                'webDir' => 'files',
                'tempPath' => '@common/uploads/temp',
                'storePath' => '@common/uploads/store',
                'rules' => [ // Правила для FileValidator
                    'maxFiles' => 20,
                    'maxSize' => 1024 * 1024 * 20 // 20 MB
                ],
            ],
        ],

    此外,将这些行添加到您的控制台配置

    'controllerMap' => [
            'file' => [
                'class' => 'yii\console\controllers\MigrateController',
                'migrationPath' => '@file/migrations'
            ],
        ],
  3. 应用迁移

    php yii migrate/up --migrationPath=@vendor/axelpal/yii2-attachments/migrations
    
  4. 将附加行为添加到您的模型(请确保您的模型有 "id" 属性)

    public function behaviors()
    {
    	return [
    		...
    		'fileBehavior' => [
    			'class' => \file\behaviors\FileBehavior::className()
    		]
    		...
    	];
    }
  5. 确保您已将 'enctype' => 'multipart/form-data' 添加到 ActiveForm 选项中

  6. 确保您在模块规则中指定了 maxFiles,并在 AttachmentsInput 中指定 maxFileCount 为您想要的数字

用法

  1. 在您的模型的 form.php 中添加文件输入

    <?= \file\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
    	]
    ]) ?>
  2. 使用小部件在 view.php 中显示模型的全部附件

    <?= \file\components\AttachmentsTable::widget(['model' => $model]) ?>
  3. (已弃用) 向您的提交按钮添加 onclick 动作,在提交表单之前上传所有文件

    <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', [
    	'class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary',
    	'onclick' => "$('#file-input').fileinput('upload');"
    ]) ?>
  4. 您可以通过调用 $model->files 来获取所有已附加文件,例如

    foreach ($model->files as $file) {
        echo $file->path;
    }