YII2十三大特性
第一(框架&项目)
1. 框架安装
2. 框架扩展安装
3. 项目初始化-->php yii init
4. 美化URL配置
'urlManager' => [ 'enablePrettyUrl' => true, 'showScriptName' => false, 'rules' => [ '<controller:[\w-]+>/<action:[\w-]+>/<id:\d+>' => '<controller>/<action>', ], ],
5. nginx的配置
server { root D:/project/chgg-erp/backend/web/; index index.html index.php; server_name local.erp.backend.com; set $yii_bootstrap "index.php"; charset utf-8; location / { index $yii_bootstrap; try_files $uri $uri/ $yii_bootstrap?$args; if (!-e $request_filename){ rewrite ^/(.*) /index.php?r=$1 last; } } location ~ ^/(protected|framework|nbproject|themes/\w+/views) { deny all; } location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ { expires 30d; } location ~ .*\.(js|css)?$ { expires 7d; } #avoid processing of calls to unexisting static files by yii location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ { try_files $uri =404; } # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # location ~ \.php$ { fastcgi_split_path_info ^(.+\.php)(.*)$; set $fsn /$yii_bootstrap; if (-f $document_root$fastcgi_script_name){ set $fsn $fastcgi_script_name; } #fastcgi_next_upstream error timeout invalid_header http_500 http_503 http_404; #fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_pass 127.0.0.1:9000; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fsn; #PATH_INFO and PATH_TRANSLATED can be omitted, but RFC 3875 specifies them for CGI fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_param PATH_TRANSLATED $document_root$fsn; } location ~ /\.ht { deny all; } }
6.读取配置文件中的配置项
\Yii::$app->configItemName
第二(数据库迁移migration)
1. 创建migration-->php yii migrate/create create_table_tablename
2. 编写migration-->
例如:编写取样申请表的migration
use yii\db\Schema; use jamband\schemadump\Migration; class m170921_093929_create_table_wms_sampling_application extends Migration { const TABLE_NAME = '{{%wms_sampling_application}}'; public function safeUp() { if ($this->db->driverName === 'mysql') { $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB COMMENT=\'取样申请表\''; } $this->createTable(self::TABLE_NAME, [ //唯一标识 'id' => $this->primaryKey() . ' AUTO_INCREMENT COMMENT \'自增ID\'', 'wms_sampling_application_code' => $this->string(45)->null()->comment('取样申请表编号'), //原料还是成品 'wms_sampling_application_type' => $this->smallInteger(1)->null()->comment('原料还是成品:1是原料,2成品'), //加工基地 'common_producer_info_id' => $this->integer(8)->null()->comment('加工基地ID'), 'common_producer_info_name' => $this->string(32)->null()->comment('加工基地名称'), //申请人 'wms_sampling_application_user_id' => $this->integer(8)->null()->comment('申请人ID'), 'wms_sampling_application_user_name' => $this->string(32)->null()->comment('申请人姓名'), 'wms_sampling_application_user_phone' => $this->string(20)->null()->comment('申请人手机号码'), //申请时间 'wms_sampling_application_apply_at' => $this->integer(10)->null()->comment('申请时间'), //申请原因 'wms_sampling_application_apply_text' => $this->text()->null()->comment('申请原因'), //审核人 'wms_sampling_application_check_user_id' => $this->integer(8)->null()->comment('审核人ID'), 'wms_sampling_application_check_user_name' => $this->string(32)->null()->comment('审核人姓名'), 'wms_sampling_application_check_user_phone' => $this->string(20)->null()->comment('审核人手机号码'), //审核时间 'wms_sampling_application_check_at' => $this->integer(10)->null()->comment('审核时间'), //审核状态与备注 'wms_sampling_application_check_status' => $this->smallInteger(1)->defaultValue(0)->comment('审核状态:0未审核,1审核通过,2审核拒绝'), 'wms_sampling_application_check_text' => $this->text()->null()->comment('审核备注'), //共有字段 'created_at' => $this->integer(10)->null(), 'updated_at' => $this->integer(10)->null(), 'is_del' => $this->boolean()->defaultValue(0), ], $tableOptions); $this->createIndex('wms_sampling_application_code',self::TABLE_NAME,'wms_sampling_application_code'); $this->createIndex('wms_sampling_application_type',self::TABLE_NAME,'wms_sampling_application_type'); $this->createIndex('wms_sampling_application_check_status',self::TABLE_NAME,'wms_sampling_application_check_status'); } public function safeDown() { $this->dropTable(self::TABLE_NAME); } }
3. 执行migration-->php yii migrate
4. 回退migration-->php yii migrate/down n
第三(代码生成器gii)
1. 配置gii
if (!YII_ENV_TEST) { // configuration adjustments for 'dev' environment $config['bootstrap'][] = 'debug'; $config['modules']['debug'] = [ 'class' => 'yii\debug\Module', ]; $config['bootstrap'][] = 'gii'; $config['modules']['gii'] = [ 'class' => 'yii\gii\Module', 'allowedIPs' => ['127.0.0.1'], 'generators' => [ 'crud' => [ //生成器名称 'class' => 'yii\gii\generators\crud\Generator', 'templates' => [ //设置我们自己的模板 //模板名 => 模板路径 'template' => '@vendor/gii_extension_template/template/crud/default', ] ] ], ]; }
2. 使用gii生成model
3. 使用gii生成curd
第四(数据模型Command/Query/ActiveRecord)
1. 使用Command即原生sql操作
例如:库存盘点清单需要查出原料入库单列表和原料出库单列表
$sql = "SELECT id in_sheet_id, wms_material_in_sheet_number in_sheet_number, common_producer_info_id producer_id, common_producer_info_name producer_name, common_producer_herb_info_id info_id, common_producer_herb_info_name info_name, common_producer_herb_grade_info_id grade_id, common_producer_herb_grade_name grade_name, SUM( IFNULL( wms_material_in_sheet_package_number, 0 ) ) AS sum_in_package_number, SUM( IFNULL( wms_material_in_sheet_in_weight, 0 ) ) AS sum_in_weight FROM {{%wms_material_in_sheet}} WHERE is_del = 0 AND wms_material_in_sheet_status = 1 AND common_producer_info_id = :common_producer_info_id AND wms_material_in_sheet_product_in_date >= :wms_check_begin_at AND wms_material_in_sheet_product_in_date <= :wms_check_end_at GROUP BY common_producer_herb_info_id, common_producer_herb_grade_info_id, wms_material_in_sheet_number"; $list = Yii::$app->db->createCommand($sql) ->bindValue(':common_producer_info_id', $common_producer_info_id) ->bindValue(':wms_check_begin_at', $wms_check_begin_at) ->bindValue(':wms_check_end_at', $wms_check_end_at)->queryAll();
使用原生sql带join操作的command
$sql = "SELECT modet.wms_stock_detail_info_relation_good_in_sheet_number in_sheet_number, mo.common_producer_info_id producer_id, mo.common_producer_info_name producer_name, mo.common_producer_herb_info_id info_id, mo.common_producer_herb_info_name info_name, mo.common_producer_herb_grade_info_id grade_id, mo.common_producer_herb_grade_name grade_name, SUM( IFNULL( modet.wms_material_out_sheet_detail_out_number, 0 ) ) AS sum_out_package_number, SUM( IFNULL( modet.wms_material_out_sheet_detail_out_weight, 0 ) ) AS sum_out_weight, SUM( IFNULL( modet.wms_material_out_sheet_detail_storage_loss_weight, 0 ) ) AS sum_out_loss_weight from {{%wms_material_out_sheet_detail}} modet LEFT JOIN {{%wms_material_out_sheet}} mo ON mo.id = modet.wms_material_out_sheet_id WHERE modet.is_del = 0 AND mo.is_del = 0 AND mo.wms_material_out_sheet_status = 1 AND mo.common_producer_info_id = :common_producer_info_id AND mo.wms_material_out_sheet_outgoing_date >= :wms_check_begin_at AND mo.wms_material_out_sheet_outgoing_date <= :wms_check_end_at GROUP BY mo.common_producer_herb_info_id, mo.common_producer_herb_grade_info_id, modet.wms_material_out_sheet_number, modet.wms_stock_detail_info_relation_good_in_sheet_number"; $list = Yii::$app->db->createCommand($sql) ->bindValue(':common_producer_info_id', $common_producer_info_id) ->bindValue(':wms_check_begin_at', $wms_check_begin_at) ->bindValue(':wms_check_end_at', $wms_check_end_at)->queryAll();
2. 使用Query操作数据表
例如:库存盘点清单功能需要查出成品入库列表和成品出库列表
$command = (new \yii\db\Query())->select([ 'id in_sheet_id', 'wms_product_in_sheet_number in_sheet_number', 'common_producer_info_id producer_id', 'common_producer_info_name producer_name', 'common_producer_herb_info_id_product info_id', 'common_producer_herb_info_name_product info_name', 'common_producer_herb_grade_info_id_product grade_id', 'common_producer_herb_grade_name_product grade_name', 'SUM( IFNULL( wms_product_in_sheet_package_number, 0 ) ) AS sum_in_package_number', 'SUM( IFNULL( wms_product_in_sheet_in_weight, 0 ) ) AS sum_in_weight' ])->from('{{%wms_product_in_sheet}}')->where('is_del = 0 AND wms_product_in_sheet_status = 1 AND common_producer_info_id = :common_producer_info_id AND wms_product_in_sheet_product_in_date >= :wms_check_begin_at AND wms_product_in_sheet_product_in_date <= :wms_check_end_at', [ ':common_producer_info_id'=>$common_producer_info_id, ':wms_check_begin_at'=>$wms_check_begin_at, ':wms_check_end_at'=>$wms_check_end_at ])->groupBy(['common_producer_herb_info_id_product', 'common_producer_herb_grade_info_id_product', 'wms_product_in_sheet_number'])->createCommand(); $list = $command->queryAll();
//注意:成品出库详情没有成品出库ID的关联字段,只能使用成品出库单号关联 //查询的入库单号应该使用出库单性情表的入库单号,,因为主表关联多个入库单,故主表入库单号为空 //分组时不应该使用入库单号,而应该使用出库单号,因为一个入库单可以分多次出库 $command = (new \yii\db\Query())->select([ 'podet.wms_product_in_sheet_number in_sheet_number', 'po.common_producer_info_id producer_id', 'po.common_producer_info_name producer_name', 'po.common_producer_herb_info_id_product info_id', 'po.common_producer_herb_info_name_product info_name', 'po.common_producer_herb_grade_info_id_product grade_id', 'po.common_producer_herb_grade_name_product grade_name', 'SUM( IFNULL( podet.wms_product_out_detail_info_out_number, 0 ) ) AS sum_out_package_number', 'SUM( IFNULL( podet.wms_product_out_detail_info_out_weight, 0 ) ) AS sum_out_weight', 'SUM( IFNULL( podet.wms_product_out_detail_info_storage_loss_weight, 0 ) ) AS sum_out_loss_weight' ])->from('{{%wms_product_out_detail_info}} podet') ->leftJoin('{{%wms_product_out_sheet}} po', 'po.wms_product_out_sheet_number = podet.wms_product_out_sheet_number') ->where('podet.is_del = 0 AND po.is_del = 0 AND po.wms_product_out_sheet_status = 1 AND po.common_producer_info_id = :common_producer_info_id AND po.wms_product_out_sheet_product_out_date >= :wms_check_begin_at AND po.wms_product_out_sheet_product_out_date <= :wms_check_end_at', [ ':common_producer_info_id'=>$common_producer_info_id, ':wms_check_begin_at'=>$wms_check_begin_at, ':wms_check_end_at'=>$wms_check_end_at ])->groupBy(['po.common_producer_herb_info_id_product', 'po.common_producer_herb_grade_info_id_product', 'po.wms_product_out_sheet_number', 'podet.wms_product_in_sheet_number'])->createCommand(); $list = $command->queryAll();
第五 (GridView/ListView/DetailView)
例如:库存盘点中创建库存盘点时展示实时库存
<?= kartik\grid\GridView::widget([ 'tableOptions' => ['class' => 'table table-striped', 'style'=>'font-size:12px;', 'id'=>'data-table'], 'layout' => "{items}", 'striped'=>false, 'hover'=>true, 'showHeader'=>true, 'showFooter'=>false, 'showPageSummary' => false, 'showOnEmpty'=>true, 'emptyText'=>'当前没有数据,请更改截止日期和存货类型后重试!', 'emptyTextOptions'=>['style'=>'color:red;font-weight:bold;text-align:center;'], 'dataProvider' => $dataProvider, 'columns' => [ [ 'label'=>'存货名称', 'attribute'=>'info_id', 'hAlign' => 'center', 'vAlign' => 'middle', 'format'=>'raw', 'group'=>true, 'value'=>function($wms){ return $wms["info_name"]; } ], [ 'label'=>'等级', 'attribute'=>'grade_id', 'hAlign' => 'center', 'vAlign' => 'middle', 'format'=>'raw', 'group'=>true, 'subGroupOf' => 0, 'value'=>function($wms){ return $wms["grade_name"]; } ], [ 'label'=>'入库单号', 'hAlign' => 'center', 'vAlign' => 'middle', 'format'=>'raw', 'value'=>function($wms){ return $wms["in_sheet_number"]; } ], [ 'label'=>'系统件数(袋)', 'hAlign' => 'center', 'vAlign' => 'middle', 'format'=>'raw', 'value'=>function($wms){ return $wms["package_number"]; } ], [ 'label'=>'盘点件数(袋)', 'hAlign' => 'center', 'vAlign' => 'middle', 'format'=>'raw', 'value'=>function($wms){ return ""; } ], [ 'label'=>'件数差异(袋)', 'hAlign' => 'center', 'vAlign' => 'middle', 'format'=>'raw', 'value'=>function($wms){ return ""; } ], [ 'label'=>'包装规格', 'hAlign' => 'center', 'vAlign' => 'middle', 'format'=>'raw', 'value'=>function($wms){ return ""; } ], [ 'label'=>'系统重量(公斤)', 'hAlign' => 'center', 'vAlign' => 'middle', 'format'=>'raw', 'value'=>function($wms){ return \common\models\Base::weightBcdiv($wms["weight"]); } ], [ 'label'=>'盘点重量(公斤)', 'hAlign' => 'center', 'vAlign' => 'middle', 'format'=>'raw', 'value'=>function($wms){ return ""; } ], [ 'label'=>'重量差异(公斤)', 'hAlign' => 'center', 'vAlign' => 'middle', 'format'=>'raw', 'value'=>function($wms){ return ""; } ], [ 'label'=>'差异说明', 'value'=>function($wms){ return ""; } ], ], ]); ?>
例如:使用GridView的导出功能,页面合计功能,表头浮动功能,列宽设置,列不换行设置
<div class="finance-detail-index"> <?php $columns = [ [ 'label'=>'基地ID', 'hAlign' => 'center', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'visible'=>true, 'hidden'=>true, 'value'=>function($model){ return $model['info_id']; } ], [ 'label'=>'品种ID', 'hAlign' => 'center', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'visible'=>true, 'hidden'=>true, 'value'=>function($model){ return $model['herb_info_id']; } ], [ 'label'=>'等级ID', 'hAlign' => 'center', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'visible'=>true, 'hidden'=>true, 'value'=>function($model){ return $model['grade_info_id']; } ], [ 'label'=>'项目ID', 'hAlign' => 'center', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'visible'=>true, 'hidden'=>true, 'value'=>function($model){ return $model['detail_type']; } ], [ 'label'=>'项目', 'hAlign' => 'center', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'group'=>true, 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ $detail_type_name = \backend\models\FinanceDetailSearch::getDetailTypeName($model['detail_type']); return $detail_type_name; } ], [ 'label'=>'品种', 'hAlign' => 'center', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'group'=>true, 'subGroupOf' => 4, 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ return $model['herb_info_name']; } ], [ 'label'=>'等级', 'hAlign' => 'center', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'group'=>true, 'subGroupOf' => 5, 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ return $model['grade_info_name']; } ], [ 'label'=>'单价(元)', 'hAlign' => 'right', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ if (!empty($model['begin_balance_weight']) && empty($model['begin_balance_unit_price'])){ return '<span class="not-set">(未知)</span>'; }else{ return \common\models\Base::moneyBcdiv($model['begin_balance_unit_price']); } } ], [ 'label'=>'重量(公斤)', 'hAlign' => 'right', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'pageSummary'=>true, 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ return \common\models\Base::weightBcdiv($model['begin_balance_weight']); } ], [ 'label'=>'金额(元)', 'hAlign' => 'right', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'pageSummary'=>true, 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ if (!empty($model['begin_balance_weight']) && empty($model['begin_balance_sum_price'])){ return '<span class="not-set">(未知)</span>'; }else{ return \common\models\Base::moneyBcdiv($model['begin_balance_sum_price']); } } ], [ 'label'=>'单价(元)', 'hAlign' => 'right', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ if (!empty($model['going_balance_weight']) && empty($model['going_balance_unit_price'])){ return '<span class="not-set">(未知)</span>'; }else{ return \common\models\Base::moneyBcdiv($model['going_balance_unit_price']); } } ], [ 'label'=>'重量增加(公斤)', 'hAlign' => 'right', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'pageSummary'=>true, 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ return \common\models\Base::weightBcdiv($model['going_balance_weight_increase']); } ], [ 'label'=>'重量减少(公斤)', 'hAlign' => 'right', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'pageSummary'=>true, 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ return \common\models\Base::weightBcdiv($model['going_balance_weight_decrease']); } ], [ 'label'=>'重量(公斤)', 'hAlign' => 'right', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'pageSummary'=>true, 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ return \common\models\Base::weightBcdiv($model['going_balance_weight']); } ], [ 'label'=>'金额增加(元)', 'hAlign' => 'right', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'pageSummary'=>true, 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ if (!empty($model['going_balance_weight_increase']) && empty($model['going_balance_sum_price_increase'])){ return '<span class="not-set">(未知)</span>'; }else{ return \common\models\Base::moneyBcdiv($model['going_balance_sum_price_increase']); } } ], [ 'label'=>'金额减少(元)', 'hAlign' => 'right', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'pageSummary'=>true, 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ if (!empty($model['going_balance_weight_decrease']) && empty($model['going_balance_sum_price_decrease'])){ return '<span class="not-set">(未知)</span>'; }else{ return \common\models\Base::moneyBcdiv($model['going_balance_sum_price_decrease']); } } ], [ 'label'=>'金额(元)', 'hAlign' => 'right', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'pageSummary'=>true, 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ if (!empty($model['going_balance_weight']) && empty($model['going_balance_sum_price'])){ return '<span class="not-set">(未知)</span>'; }else{ return \common\models\Base::moneyBcdiv($model['going_balance_sum_price']); } } ], [ 'label'=>'单价(元)', 'hAlign' => 'right', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ if (!empty($model['end_balance_weight']) && empty($model['end_balance_unit_price'])){ return '<span class="not-set">(未知)</span>'; }else{ return \common\models\Base::moneyBcdiv($model['end_balance_unit_price']); } } ], [ 'label'=>'重量(公斤)', 'hAlign' => 'right', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'pageSummary'=>true, 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ return \common\models\Base::weightBcdiv($model['end_balance_weight']); } ], [ 'label'=>'金额(元)', 'hAlign' => 'right', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'pageSummary'=>true, 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ if (!empty($model['end_balance_weight']) && empty($model['end_balance_sum_price'])){ return '<span class="not-set">(未知)</span>'; }else{ return \common\models\Base::moneyBcdiv($model['end_balance_sum_price']); } } ], [ 'class' => 'kartik\grid\ActionColumn', 'template' => '{view}', 'header'=>'操作', 'buttons' => [ 'view' => function ($url, $model, $key) { return Html::a('查看详情', ['view' ], ['class' => 'view', 'data-toggle' => 'modal', 'data-target' => '#view-modal', 'data-common_producer_info_id' => $model['info_id'], 'data-common_producer_herb_info_id' => $model['herb_info_id'], 'data-common_producer_grade_info_id' => $model['grade_info_id'], ]); }, ] ], ]; ?> <?= \kartik\grid\GridView::widget([ 'tableOptions' => ['class' => 'table table-striped', 'style'=>'font-size:12px;', 'id'=>'finance-detail'], 'layout' => "{toolbar}{items}", 'bordered' => true, 'striped' => false, 'condensed' => false, 'responsive' => true, 'hover' => true, 'floatHeader'=>false, 'floatHeaderOptions' => ['scrollingTop' => ''], 'showHeader'=>true, 'showFooter'=>false, 'beforeHeader'=>[ [ 'columns'=>[ ['content'=>'基本信息', 'options'=>['colspan'=>3, 'class'=>'text-center warning']], ['content'=>'期初余额', 'options'=>['colspan'=>3, 'class'=>'text-center warning']], ['content'=>'本期发生额', 'options'=>['colspan'=>7, 'class'=>'text-center warning']], ['content'=>'期末余额', 'options'=>['colspan'=>3, 'class'=>'text-center warning']], ['content'=>'其他', 'options'=>['colspan'=>1, 'class'=>'text-center warning']], ], 'options'=>['class'=>'skip-export'] ] ], 'showPageSummary' => true, 'showOnEmpty'=>true, 'emptyText'=>'当前没有数据!', 'emptyTextOptions'=>['style'=>'color:red;font-weight:bold;text-align:center;'], 'export' => [ 'label' => '导出', 'fontAwesome' => true, 'options'=>[ 'id'=>'export', 'float'=>'right', ], ], 'toolbar' => [ ['content'=> Html::a('业务统计报表', ['wms-statistics/index'], ['data-pjax'=>0, 'class' => 'btn btn-default', 'title'=>Yii::t('app', '业务统计报表')]) . ' '. Html::button('自定义导出', ['type'=>'button', 'title'=>Yii::t('app', '自定义导出'), 'class'=>'btn btn-success', 'onclick'=>'alert("自定义导出");']) ], '{export}', ], // 'exportConfig' => [ // \kartik\grid\GridView::EXCEL => [], // ], 'dataProvider' => $financeDetailArrayDataProvider, 'columns' => $columns, ]); ?> </div>
第六(DataProvider)
1. ActiveDataProvider
例如:
public function searchByCheckId($checkId){ $query = WmsCheckDetail::find(); $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); $query->where([ 'wms_check_id' => $checkId, 'is_summary' =>0, 'is_del' => 0, ]); return $dataProvider; }
2. SqlDataProvider
3. ArrayDataProvider
例如:根据原料或成品的数据二维数组组装ArrayDataProvider
/** * 原料列表数据提供器 * @param $common_producer_info_id * @param int $wms_check_begin_at * @param int $wms_check_end_at * @return ArrayDataProvider */ public static function getWmsMaterialInfoListProvider($common_producer_info_id, $wms_check_begin_at=0, $wms_check_end_at=0){ $wms_check_end_at = !empty($wms_check_end_at) ? $wms_check_end_at : time(); $list = self::getWmsSumList($common_producer_info_id, $wms_check_begin_at, $wms_check_end_at, 1); $provider = new ArrayDataProvider([ 'allModels' => $list, 'pagination' => [ 'pageSize' => 20, ], 'sort' => [ 'attributes' => ['in_sheet_number'], ], ]); return $provider; } /** * 获取成品数据提供器 * @param $common_producer_info_id * @param int $wms_check_begin_at * @param int $wms_check_end_at * @return ArrayDataProvider */ public static function getWmsProductInfoListProvider($common_producer_info_id, $wms_check_begin_at=0, $wms_check_end_at=0){ $wms_check_end_at = !empty($wms_check_end_at) ? $wms_check_end_at : time(); $list = self::getWmsSumList($common_producer_info_id, $wms_check_begin_at, $wms_check_end_at, 2); $provider = new ArrayDataProvider([ 'allModels' => $list, 'pagination' => [ 'pageSize' => 20, ], 'sort' => [ 'attributes' => ['in_sheet_number'], ], ]); return $provider; }
第七(验证器)
1. 必填验证器
/** * 验证规则 */ public function rules() { return [ [['common_producer_info_id', 'common_producer_herb_type', 'wms_check_user_id', 'wms_check_redo_user_id', 'created_at', 'updated_at', 'is_del'], 'integer'], //盘点时间和复核时间必须为字符串才能兼容 [[ 'wms_check_begin_at', 'wms_check_end_at', 'wms_check_at', 'wms_redo_at', 'wms_check_note', 'wms_check_redo_note', 'wms_check_manage_note'], 'string'], [['wms_check_code', 'wms_check_user_name', 'wms_check_redo_user_name'], 'string', 'max' => 32], [['common_producer_info_name'], 'string', 'max' => 50], [['wms_check_user_phone', 'wms_check_redo_user_phone'], 'string', 'max' => 20], // ['wms_check_end_at', 'string', 'message'=>'截止日期必须是字符串', 'when' => function ($model) { // return strpos(Yii::$app->request->pathInfo, "create"); // }], // ['wms_check_at', 'string', 'message'=>'盘库日期必须是字符串', 'when' => function ($model) { // return strpos(Yii::$app->request->pathInfo, "update"); // }], // ['wms_redo_at', 'string', 'message'=>'复核日期必须是字符串', 'when' => function ($model) { // return strpos(Yii::$app->request->pathInfo, "redo"); // }], //自定义验证规则,验证不能为空 ['wms_check_code', 'required', 'message'=>'编号不能为空', 'when' => function ($model) { return $model->isNewRecord; }], ['common_producer_info_id', 'required', 'message'=>'基地不能为空', 'when' => function ($model) { return $model->isNewRecord; }], ['common_producer_herb_type', 'required', 'message'=>'存货类别不能为空', 'when' => function ($model) { return $model->isNewRecord; }], ['wms_check_end_at', 'required', 'message'=>'期末不能为空', 'when' => function ($model) { return $model->isNewRecord; }], ['wms_check_user_id', 'required', 'message'=>'盘点人不能为空', 'when' => function ($model) { return strpos(Yii::$app->request->pathInfo, "update"); }], ['wms_check_redo_user_id', 'required', 'message'=>'复核人不能为空', 'when' => function ($model) { return strpos(Yii::$app->request->pathInfo, "redo"); }], ['wms_check_at', 'required', 'message'=>'盘点日期不能为空', 'when' => function ($model) { return strpos(Yii::$app->request->pathInfo, "update"); }], ['wms_redo_at', 'required', 'message'=>'复核日期不能为空', 'when' => function ($model) { return strpos(Yii::$app->request->pathInfo, "redo"); }], ]; }
2. 数据类型验证器
第八(Request与UrlManager)
1. Request
Yii::$app->request->get('name', '')
Yii::$app->request->pathInfo
2. UrlManager
例如:使用Url::to()方法
<input type="hidden" name="wms_url" value="<?= Url::to(['wms-check/create']) ?>"/> <?php $js = <<<JS $(function() { $('#data-table').attr('cell-specing', 20); }); function loadWmsList() { var url = $(":input[name=wms_url]").val(); var common_producer_herb_type = $("#wmscheck-common_producer_herb_type").val(); // var wms_check_begin_at = $("#wmscheck-wms_check_begin_at").val(); var wms_check_end_at = $("#wmscheck-wms_check_end_at").val(); // wms_check_begin_at = new Date(Date.parse(wms_check_begin_at.replace(/-/g, "/"))).getTime() / 1000; wms_check_end_at = new Date(Date.parse(wms_check_end_at.replace(/-/g, "/"))).getTime() / 1000; var href = url + "?common_producer_herb_type=" + common_producer_herb_type + "&wms_check_end_at=" + wms_check_end_at; window.location.href = href; } JS; $this->registerJs($js); ?> </div>
例如:使用Html::a()生成链接
[ 'class' => 'kartik\grid\ActionColumn', 'template' => '<li>{print}</li><li>{update}</li><li>{redo}</li><li>{view}</li><li>{delete}</li>', 'header'=>'操作', 'dropdown' => true, 'dropdownOptions' => ['class' => 'pull-right'], 'dropdownButton' => ['label' => '菜单','class'=>'btn btn-success'], 'buttons' => [ 'print' => function ($url, $model, $key) { if($model->is_del == 0){ return Html::a('打印', ['print', 'id' => $key], ['target'=>'_blank']); } }, 'update' => function ($url, $model, $key) { if($model->is_del == 0 && in_array($model->wms_check_status, array(0, 1))){ return Html::a('录入', ['update', 'id' => $key]); } }, 'redo' => function ($url, $model, $key) { if($model->is_del == 0 && in_array($model->wms_check_status, array(1))){ return Html::a('复核', ['redo', 'id' => $key]); } }, 'view' => function ($url, $model, $key) { return Html::a('查看', ['view', 'id' => $key], ['class' => ' ']); }, 'delete' => function ($url, $model, $key) { if($model->is_del == 0){ return Html::a('作废', ['delete', 'id' => $model->id], [ 'data-method' => 'post', 'data' => [ 'confirm' => '废除后无法恢复,你确定要废除此单据吗?', 'method' => 'post', ], ]) ; } }, ] ],
第九
弹出层(Modal)
<?php Modal::begin([ 'id' => 'append-modal', 'header' => '<h4 class="modal-title">选择到清单</h4>', 'footer' => '<a href="#" class="btn btn-success" id="append-ok">确定</a><a href="#" class="btn btn-default" data-dismiss="modal">关闭</a>', ]); $requestUrl = Url::toRoute('modal-union-detail-list'); $wms_profitloss_type = isset($model->wms_profitloss_type) ? $model->wms_profitloss_type : 0; $js = <<<JS $("#append").click(function() { var wms_profitloss_union_type = $("#wmsprofitloss-wms_profitloss_union_type").find("option:selected").attr("value"); var wms_profitloss_union_code = $("#wmsprofitloss-wms_profitloss_union_code").find("option:selected").attr("value"); $.get('{$requestUrl}', { 'wms_profitloss_type':'{$wms_profitloss_type}', 'wms_profitloss_union_type':wms_profitloss_union_type, 'wms_profitloss_union_code':wms_profitloss_union_code }, function (data) { $('.modal-body').html(data); } ); }); $("#append-ok").click(function() { var keys=$('#w0').yiiGridView('getSelectedRows'); for(var i=0; i<keys.length; i++){ var key = keys[i]; var tr = $("#union-list").find("tbody").find("tr").eq(key); var union_detail_id = $(tr).find("td").eq(0).text(); var info_id = $(tr).find("td").eq(0).text(); var info_name = $(tr).find("td").eq(1).text(); var grade_id = $(tr).find("td").eq(2).text(); var grade_name = $(tr).find("td").eq(3).text(); var diff_package_num = $(tr).find("td").eq(4).text(); var spec_name = $(tr).find("td").eq(5).text(); var diff_weight = $(tr).find("td").eq(6).text(); var diff_note = $(tr).find("td").eq(7).text(); var template_tr = $($('.template tbody').html().replace(/__union_detail_id__/g, union_detail_id)); $("#union_detail_id", template_tr).val(union_detail_id); $("#info_id", template_tr).val(info_id); $("#info_name", template_tr).val(info_name); $("#info_name", template_tr).text(info_name); $("#grade_id", template_tr).val(grade_id); $("#grade_name", template_tr).val(grade_name); $("#grade_name", template_tr).text(grade_name); $("#diff_package_num", template_tr).val(diff_package_num); $("#diff_package_num", template_tr).text(diff_package_num); // $("#apply_package_num", template_tr).val(apply_package_num); // $("#apply_package_num", template_tr).text(apply_package_num); $("#spec_name", template_tr).val(spec_name); $("#spec_name", template_tr).text(spec_name); $("#diff_weight", template_tr).val(diff_weight); $("#diff_weight", template_tr).text(diff_weight); // $("#apply_weight", template_tr).val(apply_weight); // $("#apply_weight", template_tr).text(apply_weight); // $("#apply_note", template_tr).val(diff_note); // $("#apply_note", template_tr).text(diff_note); // alert(template_tr.html()); $('#detail-list').append(template_tr); } $("#append-modal").modal("hide"); }); JS; $this->registerJs($js); Modal::end(); ?> <table class="table table-bordered" id="detail-list"> <tr> <td colspan="12" class="type_title"><i class="fa fa-plus" style="margin-right: 5px;"></i><?php echo Html::a('添加到清单', '#', [ 'id' => 'append', 'data-toggle' => 'modal', 'data-target' => '#append-modal', ]); ?></td> </tr> <tr> <td colspan="1" class="item-label"><label class="control-label" style="white-space:nowrap; text-align: center">存货名称</label></td> <td colspan="2" class="item-label"><label class="control-label" style="white-space:nowrap; text-align: center">等级</label></td> <td colspan="1" class="item-label"><label class="control-label" style="white-space:nowrap; text-align: center">损益件数(袋)</label></td> <td colspan="1" class="item-label"><label class="control-label" style="white-space:nowrap; text-align: center">上报件数(袋)</label></td> <td colspan="2" class="item-label"><label class="control-label" style="white-space:nowrap; text-align: center">包装规格</label></td> <td colspan="1" class="item-label"><label class="control-label" style="white-space:nowrap; text-align: center">损益重量(公斤)</label></td> <td colspan="1" class="item-label"><label class="control-label" style="white-space:nowrap; text-align: center">上报重量(公斤)</label></td> <td colspan="2" class="item-label"><label class="control-label" style="white-space:nowrap; text-align: center">上报说明</label></td> <td colspan="1" class="item-label"><label class="control-label" style="white-space:nowrap; text-align: center">操作</label></td> </tr> </table>
第十
图片上传与预览(FileInput)
<table class="table table-bordered"> <tr> <td colspan="12" class="type_title">凭证</td> </tr> <tr> <td class="item-label"> <label class="control-label" for="wmsprofitloss-wms_profitloss_apply_note" style="white-space:nowrap;">关联单号详情截图<span class="error">(必填)</span></label> </td> <td colspan="11" class="note"> <?= $form->field($model, 'wms_profitloss_apply_note[]')->widget(FileInput::classname(), [ 'options' => ['multiple' => false], 'pluginOptions' => [ // 需要预览的文件格式 'previewFileType' => 'image', // 预览的文件 // 'initialPreview' => $p1, // 需要展示的图片设置,比如图片的宽度等 // 'initialPreviewConfig' => $p2, // 是否展示预览图 'initialPreviewAsData' => true, // 异步上传的接口地址设置 'uploadUrl' => Url::toRoute(['/goods/async-banner']), // 异步上传需要携带的其他参数,比如商品id等 'uploadExtraData' => [ ], 'uploadAsync' => true, // 最少上传的文件个数限制 'minFileCount' => 1, // 最多上传的文件个数限制 'maxFileCount' => 10, // 是否显示移除按钮,指input上面的移除按钮,非具体图片上的移除按钮 'showRemove' => true, // 是否显示上传按钮,指input上面的上传按钮,非具体图片上的上传按钮 'showUpload' => true, //是否显示[选择]按钮,指input上面的[选择]按钮,非具体图片上的上传按钮 'showBrowse' => true, // 展示图片区域是否可点击选择多文件 'browseOnZoneClick' => true, // 如果要设置具体图片上的移除、上传和展示按钮,需要设置该选项 'fileActionSettings' => [ // 设置具体图片的查看属性为false,默认为true 'showZoom' => false, // 设置具体图片的上传属性为true,默认为true 'showUpload' => true, // 设置具体图片的移除属性为true,默认为true 'showRemove' => true, ], ], ]) ?> </td> </tr> </table>
例如:上传图片在模板中代码如下:
<tr> <td class="item-label"> <label class="control-label" for="wmsprofitloss-wms_profitloss_apply_certificate" style="white-space:nowrap;">关联单号详情截图<span class="error">(必填)</span></label> </td> <td colspan="11"> <?= $form->field($model, 'wms_profitloss_apply_certificate')->hiddenInput()->label(false) ?> <?= $form->field($model, 'wms_profitloss_apply_certificate_preview')->widget(\kartik\widgets\FileInput::className(), [ 'value' => $model->wms_profitloss_apply_certificate, 'options' => ['accept' => 'image/*'], 'pluginOptions' => [ 'previewFileType' => 'any', 'allowedFileExtensions'=>['jpg', 'jpeg', 'png', 'bmp'], 'initialPreviewAsData' => true, 'initialPreview' => [$model->wms_profitloss_apply_certificate], 'showPreview' => true, 'showCaption' => false, 'showRemove' => true, 'showUpload' => false ], 'pluginEvents' => [ "fileclear" => "function() { $('#wmsprofitloss-wms_profitloss_apply_certificate').val(''); }" ], ]) ?> </td> </tr>
在控制器中的代码如下:
//上传图片 if (!empty($_FILES['WmsProfitloss']['tmp_name']['wms_profitloss_apply_certificate_preview'])) { $key = uniqid(time()); Yii::$app->qiniu->uploadFile($_FILES['WmsProfitloss']['tmp_name']['wms_profitloss_apply_certificate_preview'], $key); $model->wms_profitloss_apply_certificate = 'http://' . Yii::$app->qiniu->getLink($key); }
第十一
消息提示框
在控制器中的写法:
\Yii::$app->getSession()->setFlash('error', 'This is the message'); \Yii::$app->getSession()->setFlash('success', 'This is the message'); \Yii::$app->getSession()->setFlash('info', 'This is the message');
在模板中的写法:
if( Yii::$app->getSession()->hasFlash('success') ) { echo yii\bootstrap\Alert::widget([ 'options' => [ 'class' => 'alert-success', ], 'body' => Yii::$app->getSession()->getFlash('success'), ]); } if( Yii::$app->getSession()->hasFlash('error') ) { echo yii\bootstrap\Alert::widget([ 'options' => [ 'class' => 'alert-error', ], 'body' => Yii::$app->getSession()->getFlash('error'), ]); }
第十二
导出EXCEL
1. 使用\kartik\grid\GridView的自带的导出EXCEL的功能
例如:需要配置导出EXCEL的具体配置,比如是否导出前表头,是否导出合计行,以及设置哪些列不导出。
<div class="finance-detail-index"> <?php $columns = [ [ 'label'=>'基地ID', 'hAlign' => 'center', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'visible'=>true, 'hidden'=>true, 'hiddenFromExport'=>true, 'value'=>function($model){ return $model['info_id']; } ], [ 'label'=>'品种ID', 'hAlign' => 'center', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'visible'=>true, 'hidden'=>true, 'hiddenFromExport'=>true, 'value'=>function($model){ return $model['herb_info_id']; } ], [ 'label'=>'等级ID', 'hAlign' => 'center', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'visible'=>true, 'hidden'=>true, 'hiddenFromExport'=>true, 'value'=>function($model){ return $model['grade_info_id']; } ], [ 'label'=>'项目ID', 'hAlign' => 'center', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'visible'=>true, 'hidden'=>true, 'hiddenFromExport'=>true, 'value'=>function($model){ return $model['detail_type']; } ], [ 'label'=>'项目', 'hAlign' => 'center', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'group'=>true, 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ $detail_type_name = \backend\models\FinanceDetailSearch::getDetailTypeName($model['detail_type']); return $detail_type_name; } ], [ 'label'=>'品种', 'hAlign' => 'center', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'group'=>true, 'subGroupOf' => 4, 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ return $model['herb_info_name']; } ], [ 'label'=>'等级', 'hAlign' => 'center', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'group'=>true, 'subGroupOf' => 5, 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ return $model['grade_info_name']; } ], [ 'label'=>'单价(元)', 'hAlign' => 'right', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ if (!empty($model['begin_balance_weight']) && empty($model['begin_balance_unit_price'])){ return '<span class="not-set">(未知)</span>'; }else{ return \common\models\Base::moneyBcdiv($model['begin_balance_unit_price']); } } ], [ 'label'=>'重量(公斤)', 'hAlign' => 'right', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'pageSummary'=>true, 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ return \common\models\Base::weightBcdiv($model['begin_balance_weight']); } ], [ 'label'=>'金额(元)', 'hAlign' => 'right', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'pageSummary'=>true, 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ if (!empty($model['begin_balance_weight']) && empty($model['begin_balance_sum_price'])){ return '<span class="not-set">(未知)</span>'; }else{ return \common\models\Base::moneyBcdiv($model['begin_balance_sum_price']); } } ], [ 'label'=>'单价(元)', 'hAlign' => 'right', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ if (!empty($model['going_balance_weight']) && empty($model['going_balance_unit_price'])){ return '<span class="not-set">(未知)</span>'; }else{ return \common\models\Base::moneyBcdiv($model['going_balance_unit_price']); } } ], [ 'label'=>'重量增加(公斤)', 'hAlign' => 'right', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'pageSummary'=>true, 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ return \common\models\Base::weightBcdiv($model['going_balance_weight_increase']); } ], [ 'label'=>'重量减少(公斤)', 'hAlign' => 'right', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'pageSummary'=>true, 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ return \common\models\Base::weightBcdiv($model['going_balance_weight_decrease']); } ], [ 'label'=>'重量(公斤)', 'hAlign' => 'right', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'pageSummary'=>true, 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ return \common\models\Base::weightBcdiv($model['going_balance_weight']); } ], [ 'label'=>'金额增加(元)', 'hAlign' => 'right', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'pageSummary'=>true, 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ if (!empty($model['going_balance_weight_increase']) && empty($model['going_balance_sum_price_increase'])){ return '<span class="not-set">(未知)</span>'; }else{ return \common\models\Base::moneyBcdiv($model['going_balance_sum_price_increase']); } } ], [ 'label'=>'金额减少(元)', 'hAlign' => 'right', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'pageSummary'=>true, 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ if (!empty($model['going_balance_weight_decrease']) && empty($model['going_balance_sum_price_decrease'])){ return '<span class="not-set">(未知)</span>'; }else{ return \common\models\Base::moneyBcdiv($model['going_balance_sum_price_decrease']); } } ], [ 'label'=>'金额(元)', 'hAlign' => 'right', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'pageSummary'=>true, 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ if (!empty($model['going_balance_weight']) && empty($model['going_balance_sum_price'])){ return '<span class="not-set">(未知)</span>'; }else{ return \common\models\Base::moneyBcdiv($model['going_balance_sum_price']); } } ], [ 'label'=>'单价(元)', 'hAlign' => 'right', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ if (!empty($model['end_balance_weight']) && empty($model['end_balance_unit_price'])){ return '<span class="not-set">(未知)</span>'; }else{ return \common\models\Base::moneyBcdiv($model['end_balance_unit_price']); } } ], [ 'label'=>'重量(公斤)', 'hAlign' => 'right', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'pageSummary'=>true, 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ return \common\models\Base::weightBcdiv($model['end_balance_weight']); } ], [ 'label'=>'金额(元)', 'hAlign' => 'right', 'vAlign' => 'middle', 'format'=>'raw', 'noWrap'=>true, 'width'=>'200px', // 'headerOptions'=>['class'=>'kv-sticky-column'], // 'contentOptions'=>['class'=>'kv-sticky-column'], 'pageSummary'=>true, 'visible'=>true, 'hidden'=>false, 'value'=>function($model){ if (!empty($model['end_balance_weight']) && empty($model['end_balance_sum_price'])){ return '<span class="not-set">(未知)</span>'; }else{ return \common\models\Base::moneyBcdiv($model['end_balance_sum_price']); } } ], [ 'class' => 'kartik\grid\ActionColumn', 'template' => '{view}', 'header'=>'操作', 'buttons' => [ 'view' => function ($url, $model, $key) { return Html::a('查看详情', ['view' ], ['class' => 'view', 'data-toggle' => 'modal', 'data-target' => '#view-modal', 'data-common_producer_info_id' => $model['info_id'], 'data-common_producer_herb_info_id' => $model['herb_info_id'], 'data-common_producer_grade_info_id' => $model['grade_info_id'], ]); }, ] ], ]; ?> <?= \kartik\grid\GridView::widget([ 'tableOptions' => ['class' => 'table table-striped', 'style'=>'font-size:12px;', 'id'=>'finance-detail'], 'layout' => "{toolbar}{items}", 'bordered' => true, 'striped' => false, 'condensed' => false, 'responsive' => true, 'hover' => true, 'floatHeader'=>false, 'floatHeaderOptions' => ['scrollingTop' => ''], 'showHeader'=>true, 'showFooter'=>false, 'beforeHeader'=>[ [ 'columns'=>[ ['content'=>'基本信息', 'options'=>['colspan'=>3, 'class'=>'text-center warning']], ['content'=>'期初余额', 'options'=>['colspan'=>3, 'class'=>'text-center warning']], ['content'=>'本期发生额', 'options'=>['colspan'=>7, 'class'=>'text-center warning']], ['content'=>'期末余额', 'options'=>['colspan'=>3, 'class'=>'text-center warning']], ['content'=>'其他', 'options'=>['colspan'=>1, 'class'=>'text-center warning']], ], 'options'=>['class'=>'skip-export'] ] ], 'showPageSummary' => true, 'showOnEmpty'=>true, 'emptyText'=>'当前没有数据!', 'emptyTextOptions'=>['style'=>'color:red;font-weight:bold;text-align:center;'], 'export' => [ 'label' => '导出', 'fontAwesome' => true, 'target'=>'_blank', 'encoding'=>'utf-8', 'options'=>[ 'id'=>'export', ], ], 'toolbar' => [ ['content'=> Html::a('业务统计报表', ['wms-statistics/index'], ['data-pjax'=>0, 'class' => 'btn btn-default', 'title'=>Yii::t('app', '业务统计报表')]) . ' '. Html::button('自定义导出', ['type'=>'button', 'title'=>Yii::t('app', '自定义导出'), 'class'=>'btn btn-success', 'onclick'=>'alert("自定义导出");']) ], '{export}', ], 'exportConfig' => [ \kartik\grid\GridView::EXCEL => [ 'label' => '导出EXCEL', 'iconOptions' => ['class' => 'text-primary'], 'showHeader' => true, 'showPageSummary' => true, 'showFooter' => true, 'showCaption' => true, 'filename' => '存货明细表('.$common_producer_info_name.')'.$searchModel->wms_statistics_begin_at.'至'.$searchModel->wms_statistics_end_at, 'alertMsg' => '确定要导出EXCEL格式文件?', 'options' => [ 'title'=>'', ], 'mime' => 'application/excel', 'config' => [ 'colDelimiter' => ",", 'rowDelimiter' => "\r\n", ], ], ], 'dataProvider' => $financeDetailArrayDataProvider, 'columns' => $columns, ]); ?> </div>
2.调用php-excel自定义导出excel
代码如下:
首先,对php-excel进行封装,形成MyExcelHelper
<?php namespace core\components; use PHPExcel; use PHPExcel_IOFactory; class MyExcelHelper extends \yii\base\Component{ /** * 将二维数组的数据转化为excel表格导出 * @param $data * @param $excel_name * @param $headers * @param $options */ public static function array2excel($data, $excel_name, $headers, $options){ $objPHPExcel = new PHPExcel(); ob_start(); if (!isset($options['creator'])){ $objPHPExcel->getProperties()->setCreator('creator'); }else{ $objPHPExcel->getProperties()->setCreator($options['creator']); } if (isset($options['last_modified_by'])){ $objPHPExcel->getProperties()->setCreator('last_modified_by'); }else{ $objPHPExcel->getProperties()->setCreator($options['last_modified_by']); } if (isset($options['title'])){ $objPHPExcel->getProperties()->setCreator('title'); }else{ $objPHPExcel->getProperties()->setCreator($options['title']); } if (isset($options['subject'])){ $objPHPExcel->getProperties()->setCreator('subject'); }else{ $objPHPExcel->getProperties()->setCreator($options['subject']); } if (isset($options['description'])){ $objPHPExcel->getProperties()->setCreator('description'); }else{ $objPHPExcel->getProperties()->setCreator($options['description']); } if (isset($options['keywords'])){ $objPHPExcel->getProperties()->setCreator('keywords'); }else{ $objPHPExcel->getProperties()->setCreator($options['keywords']); } if (isset($options['category'])){ $objPHPExcel->getProperties()->setCreator('category'); }else{ $objPHPExcel->getProperties()->setCreator($options['category']); } $header_keys = array_keys($headers); foreach ($header_keys as $header_index => $header_key){ $index_ascii = $header_index + 65; $index_chr = chr($index_ascii); $header_value = $headers[$header_key]; $objPHPExcel->setActiveSheetIndex(0)->setCellValue($index_chr.'1', $header_value); $objPHPExcel->setActiveSheetIndex(0)->getColumnDimension($index_chr)->setWidth(20); } $data_row_index = 2; foreach ($data as $row_index => $row){ $data_keys = array_keys($row); foreach ($data_keys as $column_index => $data_key){ $index_ascii = $column_index + 65; $index_chr = chr($index_ascii); $value = $row[$data_key]; $objPHPExcel->setActiveSheetIndex(0)->setCellValue($index_chr . $data_row_index, $value); } if ($data_row_index>=26){ throw new \yii\base\Exception('EXCEL表格超过26列'); }else{ $data_row_index++; } } $objPHPExcel->setActiveSheetIndex(0); $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); ob_end_clean(); header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename="' . $excel_name . '.xls"'); header('Cache-Control: max-age=0'); $objWriter->save('php://output'); exit; } /** * 将excel表格转化为二维数组的数据 * @param $excel_path * @param $data * @param $header */ public static function excel2array($excel_path, $data, $header_keys){ if(!file_exists($excel_path)){ throw new \yii\base\Exception('该EXCEL不存在!'); } $PHPReader = new \PHPExcel_Reader_Excel2007(); if(!$PHPReader->canRead($excel_path)){ $PHPReader = new PHPExcel_Reader_Excel5(); if(!$PHPReader->canRead($excel_path)){ throw new \yii\base\Exception('该EXCEL不可读'); } } $PHPExcel = $PHPReader->load($excel_path); $currentSheet = $PHPExcel->getSheet(0); $max_column_index = $currentSheet->getHighestColumn(); $max_row_index = $currentSheet->getHighestRow(); $data = array(); for($row_index=2; $row_index<=$max_row_index; $row_index++ ){ for($column_chr='A'; $column_chr<=$max_column_index; $column_chr++){ $column_ord = ord($column_chr); $column_index = $column_chr - 65; $key = $column_chr.$row_index; $value = $currentSheet->getCell($key)->getValue(); if($value instanceof PHPExcel_RichText){ //富文本转换字符串 $value = $value->__toString(); } $data[$row_index-1][$header_keys[$column_index]] = $value; } } return $data; } }
其次,在模板文件中添加导出excel的导出按钮(略)
最后,编写控制器接收参数并调用MyExcelHelper工具类导出excel
/** * 导出EXCEL */ public function actionExport(){ $division_id = \core\models\Division::getTopDivisionId(Yii::$app->user->identity->division_id,true); if (!empty($division_id)) { $common_producer_info_name = \core\models\Division::getDivisionName($division_id); }else{ $common_producer_info_name = '未知'; } $common_producer_info_id = \Yii::$app->request->get('common_producer_info_id'); $common_producer_herb_info_id = \Yii::$app->request->get('common_producer_herb_info_id'); $common_producer_grade_info_id = \Yii::$app->request->get('common_producer_grade_info_id'); $wms_statistics_begin_at_str = \Yii::$app->request->get('wms_statistics_begin_at', 0); $wms_statistics_end_at_str = \Yii::$app->request->get('wms_statistics_end_at', 0); $wms_statistics_begin_at = !empty(strtotime($wms_statistics_begin_at_str)) ? strtotime($wms_statistics_begin_at_str) : 0; $wms_statistics_end_at = !empty(strtotime($wms_statistics_end_at_str)) ? strtotime($wms_statistics_end_at_str) + 24*3600 : time(); $statistics_list = \core\models\FinanceDetail::getFinanceDetailStatistics($common_producer_info_id, $common_producer_herb_info_id, $common_producer_grade_info_id, $wms_statistics_begin_at, $wms_statistics_end_at); $data = []; foreach ($statistics_list as $model){ $detail_type_name = \backend\models\FinanceDetailSearch::getDetailTypeName($model['detail_type']); $herb_info_name = $model['herb_info_name']; $grade_info_name = $model['grade_info_name']; $begin_balance_unit_price = empty($model['begin_balance_unit_price']) ? '未知' : \common\models\Base::moneyBcdiv($model['begin_balance_unit_price']); $begin_balance_weight = $model['begin_balance_weight']; $begin_balance_sum_price = empty($model['begin_balance_sum_price']) ? '未知' : \common\models\Base::moneyBcdiv($model['begin_balance_sum_price']); $going_balance_unit_price = empty($model['going_balance_unit_price']) ? '未知' : \common\models\Base::moneyBcdiv($model['going_balance_unit_price']); $going_balance_weight_increase = $model['going_balance_weight_increase']; $going_balance_sum_price_increase = empty($model['going_balance_sum_price_increase']) ? '未知' : \common\models\Base::moneyBcdiv($model['going_balance_sum_price_increase']); $going_balance_weight_decrease = $model['going_balance_weight_decrease']; $going_balance_sum_price_decrease = empty($model['going_balance_sum_price_decrease']) ? '未知' : \common\models\Base::moneyBcdiv($model['going_balance_sum_price_decrease']); $going_balance_weight = $model['going_balance_weight']; $going_balance_sum_price = empty($model['going_balance_sum_price']) ? '未知' : \common\models\Base::moneyBcdiv($model['going_balance_sum_price']); $end_balance_unit_price = empty($model['end_balance_unit_price']) ? '未知' : \common\models\Base::moneyBcdiv($model['end_balance_unit_price']); $end_balance_weight = $model['end_balance_weight']; $end_balance_sum_price = empty($model['end_balance_sum_price']) ? '未知' : \common\models\Base::moneyBcdiv($model['end_balance_sum_price']); $data[] = [ 'detail_type_name'=>$detail_type_name, 'herb_info_name'=>$herb_info_name, 'grade_info_name'=>$grade_info_name, 'begin_balance_unit_price'=>$begin_balance_unit_price, 'begin_balance_weight'=>$begin_balance_weight, 'begin_balance_sum_price'=>$begin_balance_sum_price, 'going_balance_unit_price'=>$going_balance_unit_price, 'going_balance_weight_increase'=>$going_balance_weight_increase, 'going_balance_sum_price_increase'=>$going_balance_sum_price_increase, 'going_balance_weight_decrease'=>$going_balance_weight_decrease, 'going_balance_sum_price_decrease'=>$going_balance_sum_price_decrease, 'going_balance_weight'=>$going_balance_weight, 'going_balance_sum_price'=>$going_balance_sum_price, 'end_balance_unit_price'=>$end_balance_unit_price, 'end_balance_weight'=>$end_balance_weight, 'end_balance_sum_price'=>$end_balance_sum_price, ]; } $excel_name = '存货明细表('.$common_producer_info_name.')'.$wms_statistics_begin_at_str.'至'.$wms_statistics_end_at_str; $headers = [ 'detail_type_name'=>'项目', 'herb_info_name'=>'品种', 'grade_info_name'=>'等级', 'begin_balance_unit_price'=>'单价(元)', 'begin_balance_weight'=>'重量(公斤)', 'begin_balance_sum_price'=>'金额(元)', 'going_balance_unit_price'=>'项目', 'going_balance_weight_increase'=>'重量增加(公斤)', 'going_balance_sum_price_increase'=>'金额增加(元)', 'going_balance_weight_decrease'=>'重量减少(公斤)', 'going_balance_sum_price_decrease'=>'金额减少(元)', 'going_balance_weight'=>'重量(公斤)', 'going_balance_sum_price'=>'金额(元)', 'end_balance_unit_price'=>'单价(元)', 'end_balance_weight'=>'重量(公斤)', 'end_balance_sum_price'=>'金额(元)', ]; $options = [ 'creator'=>'中国汉广集团IT信息中心', 'last_modified_by'=>'中国汉广集团IT信息中心', 'title'=>$excel_name, 'subject'=>$excel_name, 'description'=>'存货明细表', 'keywords'=>'原料成品在途', 'category'=>'存货明细表', ]; \core\components\MyExcelHelper::array2excel($data, $excel_name, $headers, $options); }
YII2十三大特性的更多相关文章
- YII2十三大特性2
第十三 场景(scenario)的使用 例如:有三个场景,分别为创建,更新,确认回款 首先,定义所有的场景,及规则,如下所示: <?php namespace core\models; use ...
- 如何使用yii2的缓存依赖特性
目录 如何使用yii2的缓存依赖特性 概述 页面缓存 缓存依赖 链式依赖 总结 如何使用yii2的缓存依赖特性 概述 缓存是Yii2的强大特性之一,合理使用缓存技术可以有效地减小服务器的访问压力.Yi ...
- Yii2版本号新特性简单介绍
Yii2 Beta版本号在今年4月份公布.眼下正在改动问题和完好文档中. Yii2要求PHP版本号不低于5.4,主要有例如以下改进: 1)支持PHP框架间协作组制定的PSR-4标准,这简化了文件夹并提 ...
- yii2实战教程之新手入门指南-简单博客管理系统
作者:白狼 出处:http://www.manks.top/document/easy_blog_manage_system.html 本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文 ...
- yii2使用相关记录
#Yii::$app->user 是指yii\web\User这个类 #yii2在命令行下执行 D: cd D:\wnmp\php5 php D:\wnmp\www\yii2\yii test/ ...
- PHP的学习--Traits新特性
在阅读yii2源码的时候接触到了trait,就学习了一下,写下博客记录一下. 自 PHP 5.4.0 起,PHP 实现了代码复用的一个方法,称为 traits. Traits 是一种为类似 PHP 的 ...
- Yii2初谈
Yii2发布有两个月时间了,一直没有去仔细关注过. 今天在回顾PSR标准时,稍稍扫了一眼Yii2.它的命名风格还是一如既往的与Zend那种既首字母大写又还要下划线连接的很二的命名风格格格不入.其实我看 ...
- yii2高级应用
public function searchWithRelated() { $criteria = new CDbCriteria; $criteria->together = ...
- Yii2 GridView自定义链接之重写 ActionColumn
最近刚开始用yii2,真是超棒的,但是也有许多不足的地方,今天要说的就是GridView链接问题. <?= GridView::widget([ 'dataProvider' => $ ...
随机推荐
- PAT A1146 Topological Order (25 分)——拓扑排序,入度
This is a problem given in the Graduate Entrance Exam in 2018: Which of the following is NOT a topol ...
- Echo团队Alpha冲刺随笔 - 第四天
项目冲刺情况 进展 前端:完成了差不多一半,小程序部分界面基本完工,WEB端也完成了一部分 后端:也完成了大半了 问题 后端文件上传还没解决 心得 进度还行,团队配合都还不错 今日会议内容 黄少勇 今 ...
- 博客搬家了qwq
呃,其实也不是搬家了,应该算是逐渐过渡qwq \[\color{skyblue}{Orchid} \color{purple}{any}\] 好的,我在学校里并不可以用Hexo,因为deploy总是挂 ...
- 数据库连接不关闭造成的问题以及RowSet的使用
这几天给项目做性能压力测试,发现一个方法压力200之后就会把整个系统弄停掉.仔细检查发现是开发人员调用数据库的写法有问题.用的是spring的jdbcTemplate,在使用回调的时候,在回调里又做了 ...
- (转)vim中多行注释
1.多行注释: 1. 首先按esc进入命令行模式下,按下Ctrl + v,进入列(也叫区块)模式; 2. 在行首使用上下键选择需要注释的多行; 3. 按下键盘(大写)“I”键,进入插入模式: ...
- 关于PCB开窗
如果走220V,那么线宽一点,一般高电压下面不覆铜 https://blog.csdn.net/zhy295006359/article/details/77412566 假设感觉需要走大电流,那么就 ...
- Bootstrap动态轮播
一.前台界面 <%@ page language="java" contentType="text/html; charset=UTF-8" pageEn ...
- jQuery与js例子
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 实现Repeater控件的记录单选(二)
前一篇<实现Repeater控件的记录单选>http://www.cnblogs.com/insus/p/7426334.html 虽然可以实现对Repeater控件的记录进行单选,但是, ...
- 浅淡volatile原理
Volatile是轻量级的synchronized,它在多处理器开发中保证了共享变量的“可见性” Volatile的官方定义 Java语言规范第三版中对volatile的定义如下: java编程语言允 ...