anli/yii2-helper

Yii 2.0 辅助工具

安装次数: 441

依赖: 1

建议者: 0

安全性: 0

星星: 0

关注者: 1

分支: 3

开放问题: 0

类型:yii2-extension

2.0.0 2016-01-27 04:03 UTC

This package is not auto-updated.

Last update: 2019-08-27 19:25:06 UTC


README

Yii 2.0 辅助工具

安装

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

运行以下命令之一:

php composer.phar require --prefer-dist anli/yii2-helper "*"

或者

"anli/yii2-helper": "*"

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

模态框

添加到您的布局文件

use anli\helper\assets\ModalAsset;
...
<!-- BEGIN MODAL -->
<?php Modal::begin(['id' => 'modal', 'size' => 'modal-lg',]);
    echo "<div id='modalContent'><div style=\"text-align:center\">" . Html::img('@web/images/ajax-loader.gif') . "</div></div>";
Modal::end();?>
<!-- END MODAL -->

要创建一个打开模态框的按钮,更新其 value 为控制器 URL 并将 class 更改为 showModalButton。例如

Html::a('<i class="fa fa-plus"></i>', false, ['value' => Url::to(['tenant/create']), 'title' => 'Create Tenant', 'class' => 'showModalButton btn btn-circle green-haze btn-sm'])

要使用 AJAX 验证和提交

更新控制器操作为

$model = new Tenant();

if ($model->load(Yii::$app->request->post()) && $model->save()) {
     Yii::$app->response->format = Response::FORMAT_JSON;
     return [
        'message' => 'successful',
     ];
}

if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()) && isset($_POST['ajax'])) {
    Yii::$app->response->format = Response::FORMAT_JSON;
    return \yii\widgets\ActiveForm::validate($model);
}

return $this->renderAjax('create', [
    'model' => $model
]);

更新视图 _form

<?php $form = ActiveForm::begin(['id' => $model->formName(),
    'options' => ['class' => 'modalSubmit'],
    'enableAjaxValidation' => false,
    'enableClientValidation' => true,
]); ?>

导入操作

在视图页面添加按钮

Html::a('<i class="fa fa-download"></i>', false, ['value' => Url::to(['tenant/import']), 'title' => 'Import Tenant', 'class' => 'showModalButton btn btn-circle blue btn-sm']),

将按钮添加到控制器中的 actions 函数

'import' => [
    'class' => 'anli\helper\actions\ImportAction',
    'importModelName' => '\anli\auth0\models\Tenant',
    'attributes' => [
        'name' => 'name',
    ],
],

导出操作

在视图页面添加按钮

Html::a('<i class="fa fa-cloud-download"></i>', ['tenant/export'], ['title' => 'Export Tenant', 'class' => 'btn btn-circle yellow btn-sm', 'data-pjax' => 0]),

将按钮添加到控制器中的 actions 函数

'export' => [
    'class' => 'anli\helper\actions\ExportAction',
    'query' => Tenant::find(),
    'attributes' => [
        'name' => 'name',
    ],
],

Gridview 中的复选框列

在视图页面,通过以下方式在 GridView 小部件的 columns 部分添加

...
->checkbox()
...

通过以下方式在模型列文件中添加 checkbox() 函数

/**
 * @return mixed
 */
public function checkbox()
{
    $this->columns = array_merge($this->columns, [
        [
            'class' => 'yii\grid\CheckboxColumn',
        ],
    ]);
    return $this;
}

在视图页面添加按钮

Html::a('<i class="fa fa-trash"></i> Delete selected', '#', ['title' => 'Delete Selected Tenant', 'class' => 'selectCheckboxButton', 'value-url' => 'http://url/to/controller/action', 'value-id' => 'my-gridview-id',]);

在控制器中添加 action

/**
 * @param string
 * @return string
 */
public function actionDeleteCheckbox($keylist)
{
    $keylist = explode(",", $keylist);

    $count = count($keylist);

    foreach ($keylist as $id) {
        $this->findModel($id)->delete();
    }

    Yii::$app->getSession()->setFlash('success', "You have deleted $count tenant!");

    return $this->goBack();

    Yii::$app->response->format = Response::FORMAT_JSON;
    return [
       'message' => $keylist,
    ];
}

按钮组

将其添加到视图页面

use anli\metronic\widgets\ButtonGroup;
...

ButtonGroup::widget(['buttons' => [$button1, $button2, $button3]])

删除所有操作

将其添加到控制器中的 actions 函数

...
return [
    'delete-all' => [
        'class' => 'anli\helper\actions\DeleteAllAction',
        'modelFullName' => self::MODEL_FULL_NAME,
        'conditions' => ['tenant_id' => Yii::$app->tenant->identity->id, 'user_id' => Yii::$app->user->id],
    ],

Cal Heatmap

使用以下方式添加您的视图文件

use anli\helper\widgets\CalHeatmap;
...
<?= CalHeatmap::widget(['url' => ['timesheet/get-timeslip-heatmap-data'], 'id' => 'timeslip-heatmap', 'legend' => '[1]', 'legendColors' => '["#efefef", "maroon"]', 'onClickUrl' => Url::to(['timesheet/list', 'userId' => Yii::$app->user->id])]); ?>

对于热图数据,添加您的控制器

/**
 * @param mixed $id
 * @return string
 */
public function actionGetTimeslipHeatmapData($id = null)
{
    if (!isset($id)) {
        $id = Yii::$app->user->id;
    }

    $data = [];
    foreach (User::findOne($id)->timeslips as $record) {
        $date = new \DateTime($record['timesheet_date']);
        $data[$date->getTimestamp()] = (float)1;
    }

    Yii::$app->response->format = Response::FORMAT_JSON;
    return $data;
}

对于 onClickJs 事件,添加您的控制器

/**
 * @param integer $userId
 * @param integer $timesheetDate
 * @return mixed
 */
 public function actionList($userId, $date)
 {
     return $this->renderAjax('list', [
         'query' => Timesheet::find()
            ->byUser($userId)
            ->byTimesheetDate(strtotime($date))
     ]);
 }

Morris Js

将其添加到您的视图

use anli\helper\widgets\MorrisJs;
...
<?= MorrisJs::widget(['url' => Url::to(['timesheet/get-morris-js', 'userId' => $user->id]), 'xkey' => "'period'", 'ykeys' => "['worked']", 'labels' => "['Hours']"]); ?>

将其添加到您的控制器

/**
 * @return string
 */
public function actionGetMorrisJs($userId = null)
{
    $user = User::findOne($userId);

    $array = [];
    $x = 0;
    for ($i = 6; $i >= 0 ; $i--) {
        $date = new \DateTime("today -$i months");
        $array[$x]['period'] = $date->format('F Y');
        $array[$x]['worked'] = (float)$user->getTimesheets()->byTimesheetMonth($date->format('Y-m-01'))->sum('work_hour');
        $x++;
    }

    Yii::$app->response->format = Response::FORMAT_JSON;
    return [
        'data' => $array,
        'xkey' => "'period'",
        'ykeys' => "['worked']",
        'labels' => "['Hours']",
    ];
}

日期分页器

将其添加到您的视图文件

use anli\helper\widgets\DatePaginator;
...
<?php
    $selectedDate = (0 < $dataProvider->totalCount) ? $dataProvider->getModels()[0]['timesheet_date'] : Yii::$app->getRequest()->getQueryParam('TimesheetSearch')['timesheet_date'];

    echo DatePaginator::widget(['id' => 'timesheet-date-paginator', 'selectedDate' => $selectedDate,
        'queryUrl' => Url::to(['/user/dashboard']) . '?TimesheetSearch%5Btimesheet_date%5D=',
    ]);
?>

更改您的控制器

/**
 * Logout a user with auth0
 * @return mixed
 */
public function actionDashboard()
{
    Yii::$app->user->setReturnUrl(['/' . $this->getRoute()]);

    $query = Timesheet::find()
    ->byUser()
    ->orderBy('timesheet_date DESC, start_time DESC');

    if (null === (Yii::$app->getRequest()->getQueryParam('TimesheetSearch')['timesheet_date'])) {
        $query->byTimesheetDate(strtotime(User::LoginUser()->getTimesheets()->max('timesheet_date')));
    }

    $searchModel = new TimesheetSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams, $query);

    return $this->render('dashboard', [
        'user' => User::LoginUser(),
        'timesheetQuery' => $query,
        'dataProvider' => $dataProvider,
        'searchModel' => $searchModel,
    ]);
}

创建操作

将其添加到控制器中的 action 部分

'copy' => [
    'class' => 'anli\helper\actions\CreateAction',
    'model' => new Timesheet,
    'defaultValues' => function () {
        $model = Timesheet::findOne(Yii::$app->getRequest()->getQueryParam('id'));
        return [
            'timesheet_date' => date('Y-m-d'),
            'start_time' => Timesheet::find()->byUser()->byTimesheetDate('now')->max('end_time'),
            'customer_id' => $model->customer_id,
            'is_chargeable' => $model->is_chargeable,
            'period_start_date' => $model->period_start_date,
            'period_end_date' => $model->period_end_date,
            'name' => $model->name,
        ];
    }
    'isSaveAndNew' => (isset($_POST['save-and-new'])),
    'saveAndNewUrl' => Url::to(['timesheet/create']),
],

更新操作

将其添加到控制器中的 action 部分

'update' => [
    'class' => 'anli\helper\actions\UpdateAction',
    'model' => Timesheet::findOne(Yii::$app->getRequest()->getQueryParam('id')),
    'isSaveAndNew' => (isset($_POST['save-and-new'])),
    'saveAndNewUrl' => Url::to(['timesheet/create']),
],

Toastr

将其添加到您的布局

<?php Pjax::begin(['id' => 'pjax-message']); ?>
<?php anli\helper\widgets\Toastr::widget(); ?>
<?php Pjax::end(); ?>

自动完成

将其添加到您的表单

<?= $form->field($model, 'name')->widget(AutoComplete::classname(), [
    'clientOptions' => [
        'source'=> new JsExpression("function(request, response) {
            $.getJSON('" . Url::to(['/invoice/name-auto-complete']) . "', {
                term: request.term,
                supplierId: $(\"#invoice-supplier_id\").val(),
            }, response);
        }"),
        'minLength' => 2,
    ],
    'options' => ['class' => 'form-control', 'placeholder' => 'Filter as you type ...'],
]); ?>

将其添加到控制器操作的 action 部分

'name-auto-complete' => [
    'class' => 'anli\helper\actions\AutoCompleteAction',
    'query' => Invoice::find()
        ->select(['name as label'])
        ->andWhere(['supplier_id' => Yii::$app->getRequest()->getQueryParam('supplierId')])
        ->andWhere(['like', 'name', Yii::$app->getRequest()->getQueryParam('term')])
        ->limit(20)
        ->distinct(),
    'term' => Yii::$app->getRequest()->getQueryParam('term'),
],