letsjump/yii2-easy-ajax 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

letsjump/yii2-easy-ajax

Composer 安装命令:

composer require letsjump/yii2-easy-ajax

包简介

EasyAjax are a bunch of Yii methods that minimize the amount of code you need to write to interact with Ajax CRUD, notifies, modals, tabs, pjax-reloads, form validations among others...

README 文档

README

Relax your keyboard with Yii2 EasyAjax

EasyAjax are a bunch of Yii methods that minimize the amount of code you need to write to interact with Bootstap UI and with Javascript in general.

Notifies, modals, tabs, pjax-reloads, form validation among others can now be set up and launched with only a line of code into the controller's action response.

For example, EasyAjax::modal('My modal content') opens a modal with "My modal content" as content, while EasyAjax::reloadPjax(['#p0']) reloads the pjax-container identified by id="p0"

EasyAjax further provides:

  • Complete and ready-to-use ajax CRUD, thanks to the integrated Gii generator
  • Fully configurable options both globally and action-specific
  • Customizable HTML templates
  • Extensible with your own methods

Installation

The preferred way to install this extension is through composer.

Either run

composer require --prefer-dist letsjump/yii2-easy-ajax

or add

"letsjump/yii2-easy-ajax": "~1.0.0"

to the require section of your composer.json.

Configuration

To use this extension, add the following code to your web application configuration (config/web.php):

'components' => [
    'easyAjax' => [
        'class' => 'letsjump\easyAjax\EasyAjaxBase',
        'customOptions' => [
            /* refer to plugin documentation */
        ]
    ],
]

To use the integrated Gii generator, add the following code to your application configuration:

if (YII_ENV_DEV) {
    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = [
        'class' => \yii\gii\Module::class,
        // uncomment the following to add your IP if you are not connecting from localhost.
        'allowedIPs' => ['127.0.0.1', '::1', /** your IPs */],
        'generators' => [
            'crud' => [ 
                'class'     => 'letsjump\easyAjax\gii\crud\Generator',
                'templates' => [ //setting for out templates
                    'yii2-easy-ajax' => '@vendor/letsjump/yii2-easy-ajax/gii/crud/default',
                ]
            ],
        ],
    ];
}

Please note: The integrated Gii generator allows you to generate the code for AJAX as well as the standard CRUD.

Usage

1. Requests

EasyAjax requests are simple jQuery AJAX requests that need to refer to a controller action appropriately configured:

The easiest way to perform an EasyAjax request to a controller action is adding the data-yea=1 attribute to the Html tag in charge of the onclick javascript event:

<a data-yea="1" class="btn btn-lg btn-success" href="<?= \yii\helpers\Url::to(['controller/action-notify']) ?>">notify something</a>

or

<button data-yea="1" data-form-id="friend-form" type="submit" class="btn btn-primary pull-right">Save</button>

NOTE:

To explore any other Html attributes available and to know all the details, please refer to the guide

2. Responses

The controller actions interacting with EasyAjax should return a Json array, and they only need to contain one or more EasyAjax methods in their response array.

In the following example...

public function actionSaveMyModel()
{
    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

    // your model validation and save logic...

    return [
        \letsjump\easyAjax\EasyAjax::modalClose(),
        \letsjump\easyAjax\EasyAjax::reloadPjax(['#p0']),
        \letsjump\easyAjax\EasyAjax::notifySuccess('Your model has been saved')
    ];
}

... EasyAjax will:

Here are the available methods in detail:

Modals

With EasyAjax, you can fire and configure a Bootstrap Modal using the following: EasyAjax::modal(content, title, form_id, size, footer, options)

public function actionModal()
{
    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    
    return [
        \letsjump\easyAjax\EasyAjax::modal('This is the modal content', 'Modal title'),
    ];
}

It is also available a method to remotely close a Modal which is actually open in the UI:

public function actionCloseModal()
{
    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    
    return [
        \letsjump\easyAjax\EasyAjax::modalClose(),
    ];
}

You can edit the modal layout and many other settings. Please refer to the guide for all the available options.

Notify

EasyAjax Notify allows to control the Bootstrap Notify plugin. The plugin assets (bootstrap-notify.js and animate.js) are bundled within EasyAjax.

Tip: You can disable the asset inclusion if it is already bundled in your application

To fire a Notify, you can use \letsjump\easyAjax\EasyAjax::notify(message, title, settings). In the settings parameter, you should specify the type of notification displayed (Notify::TYPE_INFO (blue), Notify::TYPE_SUCCESS (green), Notify::TYPE_WARNING (yellow) or Notify::TYPE_DANGER (red)).

To speed up your coding, I have also added some shortcut methods for the most common notification types: EasyAjax::notifyInfo(message), EasyAjax::notifySuccess(message), EasyAjax::notifyWarning(message), EasyAjax::notifyDanger(message).

Example:

public function actionNotify()
{
    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    return [
        \letsjump\easyAjax\EasyAjax::notifyInfo('This is an Info Notify!')
    ];
}

Note: Actually notify doesn't refer to the Yii2 flash message session array. Please open an issue if you think it is needed.

Refer to the guide for all the available options and template manipulation.

Pjax Reload

The EasyAjax PjaxReload (EasyAjax::pjaxReload(['#myPjaxID0', '#myPjaxID1', ...])) method allows to reload one or more Pjax containers.

public function actionPjaxReload()
{
    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    
    return [
        \letsjump\easyAjax\EasyAjax::reloadPjax(['#p0'])
    ];
}

Refer to the guide for detailed informations.

Form Validation

The form validation (EasyAjax::formValidation(['#my-form-id'=>ActiveForm::validate(MyModelClass)])) method allows to display the validation results for the specified form. It will send the validation results for each form field specified by the #form-id attribute to display its error messages.

public function actionValidateForm()
{
    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    $contactForm                = new ContactForm();
    
    return [
        \letsjump\easyAjax\EasyAjax::formValidation(['#contact-form' => \yii\widgets\ActiveForm::validate($contactForm)])
    ];
}

Refer to the guide for detailed informations.

Ajax CRUD with Gii

The bundled Gii generator within EasyAjax allows you to instantly create the Ajax CRUD controller and views.

Gii module

This will generate a CRUD schema which is identical to the Yii2 original one, with an added actionModal($id=null) into the controller code, plus its relative myViewFolder/_modal.php view in charge of creating or updating the data in an Ajax modal.

You can switch the CRUD behavior to Ajax modal by simply setting the 'modal' parameter of the integrated ActionColumn method :

// myViewFolder/index.php 

<?= \yii\grid\GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        'id',
        // ... your gridview fields
        [
            'class' => 'letsjump\easyAjax\helpers\ActionColumn',
            'modal' => true
        ],
    ],
]); ?>

BONUS: Deleting a record doesn't imply a complete page refresh, therefore the GridView pagination will not be affected.

Refer to the guide for all the available options.

Ajax Tabs

EasyAjax Tab (EasyAjax::tab('tab-id', 'content to inject')) is a simple and very basic way to update the content of a Bootstrap Tab with an ajax response from a controller.

View

In the \yii\bootstrap\Tabs widget for each tab item, you must:

  • Include a linkOptions parameter with a reference to the controller action Url and a data-yea=1 parameter which will fire the request.
  • Set the tab container ID ('options' => ['id' => 'yourTabID']) for a stable reference to its content.
<?= \yii\bootstrap\Tabs::widget([
    'items' => [
        [
            'label'       => 'Rome',
            'linkOptions' => [
                'data-href' => \yii\helpers\Url::to(['site/tab', 'id' => 'rome',]),
                'data-yea'  => 1
            ],
            'options'     => ['id' => 'rome'],
        ],
        // ... other tabs
    ]
]) ?>

Controller

Just include the EasyAjax method EasyAjax::tab(tab-id, content) into the controller action response array:

public function actionTab($id)
{
    $date = new \DateTimeImmutable('now');
    
    $content = [
        'rome' => $date->setTimezone(new \DateTimeZone('Europe/Rome'))->format('l jS \of F h:i:s A'),
        'london' => $date->setTimezone(new \DateTimeZone('Europe/London'))->format('l jS \of F h:i:s A'),
        'new-york' => $date->setTimezone(new \DateTimeZone('America/New_York'))->format('l jS \of F h:i:s A'),
        'calcutta' => $date->setTimezone(new \DateTimeZone('Asia/Calcutta'))->format('l jS \of F h:i:s A'),
    ];
    
    if ( ! array_key_exists($id, $content)) {
        throw new \yii\web\BadRequestHttpException('Your request is invalid');
    }
    
    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    
    return [
        \letsjump\easyAjax\EasyAjax::tab($id, '<p>' . $content[$id] . '</p>')
    ];
}

Warning: tab-id must be specified without the hashtag (#).

Refer to the guide for all the available options.

Content replace

EasyAjax ContentReplace(['#container1-id'=>'New content', '#container2-id'=>'New content', ...]) replaces the content of a specific Html tag with the code sent by the EasyAjax response. It uses the jQuery.html() standard method.

public function actionContentReplace()
{
    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    
    return [
        \letsjump\easyAjax\EasyAjax::contentReplace(['#time-placeholder' => date('d/m/Y H:i:s')])
    ];
}

Refer to the guide for detailed informations.

Confirms

You can use the EasyAjax confirm('message', 'url') method to fire a Javascript Window confirm() from a controller action. By clicking on the "OK" button it will fire an Ajax request to the action specified in the url parameter.

public function actionConfirm()
{
    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    
    return [
        \letsjump\easyAjax\EasyAjax::confirm('This will fire a growl. Ok?', \yii\helpers\Url::to(['site/notify']))
    ];
}

Refer to the guide for detailed informations.

Security

See SECURITY.md

Contributing

See CONTRIBUTING.md

Credits

Yiisoft for the best PHP framework for large-scale application (my own opinion), Twitter Bootstrap, and the Bootstrap Notify plugin. The Code of Conduct is adapted from the Contributor Covenant

License

See LICENSE.md

letsjump/yii2-easy-ajax 适用场景与选型建议

letsjump/yii2-easy-ajax 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 424 次下载、GitHub Stars 达 5, 最近一次更新时间为 2018 年 11 月 16 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「bootstrap」 「notify」 「modal」 「tabs」 「user interface」 「yii2」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 letsjump/yii2-easy-ajax 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 letsjump/yii2-easy-ajax 我们能提供哪些服务?
定制开发 / 二次开发

基于 letsjump/yii2-easy-ajax 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 424
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 6
  • 点击次数: 25
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 5
  • Watchers: 2
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2018-11-16