Code Monkey home page Code Monkey logo

yii2-ajax-submit-button's Introduction

AjaxSubmitButton for Yii 2

=====================================

Latest Stable Version Total Downloads License Monthly Downloads Yii2

This is the powerful AjaxSubmitButton widget that renders an ajax button which is very similar to ajaxSubmitButton from Yii1 for Yii 2, but has many useful functions.

Basic Example

Example of usage of the widget with a custom widget (in this case Select2 widget).

The view:

use demogorgorn\ajax\AjaxSubmitButton;

<?php echo Html::beginForm('', 'post', ['class'=>'uk-width-medium-1-1 uk-form uk-form-horizontal']); ?>
      
<?= Select2::widget([
    'name' => 'country_code',
    'data' => Country::getAllCountries(),
    'options' => [
        'id' => 'country_select',
        'multiple' => false, 
        'placeholder' => 'Choose...',
        'class' => 'uk-width-medium-7-10']
     ]);
?>
       
<?php AjaxSubmitButton::begin([
    'label' => 'Check',
    'ajaxOptions' => [
        'type'=>'POST',
        'url'=>'country/getinfo',
        'success' => new \yii\web\JsExpression('function(html){
            $("#output").html(html);
            }'),
    ],
    'options' => ['class' => 'customclass', 'type' => 'submit'],
    ]);
    AjaxSubmitButton::end();
?>
            
<?php echo Html::endForm(); ?>

<div id="output"></div>

Please note: that #output is a div element which will be updated.

In controller:

public function actionGetinfo()
{
    if(!isset($_POST['country_code']) || empty($_POST['country_code']))
        return;

    $code = $_POST['country_code'];

    return $this->renderAjax('resultwidget', ['code' => $code]);
}

Example of usage with ActiveForm and client validation

The view:

    $form = ActiveForm::begin([
               'id' => 'add-form',
               'options' => ['class' => 'form-inline'],
            ]);

    ...

    AjaxSubmitButton::begin([
        'label' => 'Add',
        'useWithActiveForm' => 'add-form',
        'ajaxOptions' => [
            'type' => 'POST',
            'success' => new \yii\web\JsExpression("function(data) {
                if (data.status == true) 
                {
                    closeTopbar();
                }                                            
            }"),
        ],
        'options' => ['class' => 'btn btn-primary', 'type' => 'submit', 'id' =>'add-button'],
    ]);
    AjaxSubmitButton::end();
    
    ActiveForm::end()

As you can see it's quite easy to use the widget with ActiveForm - enough to set the ActiveForm's id to the 'useWithActiveForm' variable. (In this case id is 'add-form', without '#' symbol!).

Client validation

As I said before the widget can be used with ActiveForm and client validation enabled. If you wish to disable it, just set ActiveForm's 'enableClientValidation' to false.

    $form = ActiveForm::begin([
                'id' => 'filters-form',
                'enableClientValidation' => false
            ]);

Preloader use

It's possible to use the widget with your own custom preloader.

<?php AjaxSubmitButton::begin([
    'label' => 'Check',
    'ajaxOptions' => [
        'type'=>'POST',
        'url'=>'country/getinfo',
        'beforeSend' => new \yii\web\JsExpression('function(html){
            ... show preloader...
            }'),
        'success' => new \yii\web\JsExpression('function(html){
            ... hide preloader ...
            }'),
    ],
    'options' => ['class' => 'customclass', 'type' => 'submit'],
    ]);
    AjaxSubmitButton::end();
?>

File Uploads

AjaxSubmitButton fully supports file uploads. For example (look at the comments):

<?php AjaxSubmitButton::begin([
            'label' => 'Сохранить',
            'useWithActiveForm' => 'add-form',
            'ajaxOptions' => [
                'type' => 'POST',
                'processData' => false, // Don't process the files
                'contentType' => false, // Set content type to false as jQuery will tell the server its a query string request
                'data' => new \yii\web\JsExpression("new FormData($('#add-form')[0])"), // Do not stringify the form
                'success' => new \yii\web\JsExpression("function(data) {
                if (data.status == true) 
                {
                    // process result
                }                                            
            }"),
            ],
            'options' => ['class' => 'btn btn-primary', 'type' => 'submit', 'id' =>'add-button'],
        ]);
        AjaxSubmitButton::end(); ?>

Widget's options

Variable Description Type
ajaxOptions ajax options Array
options HTML attributes and other options of the widget's container tag Array
tagName the tag to use to render the button (by default is 'button'. You can specify, for example, 'a' tag) String
label button's label String
icon button's icon String (e.g. 'fa fa-download')
iconPosition button icon position const (ICON_POSITION_LEFT or ICON_POSITION_RIGHT)
encodeLabel whether the label should be HTML-encoded Boolean
clickedButtonVarName js object name. It is unused when useWithActiveForm is enabled String
useWithActiveForm whether the button should not be used with ActiveForm. the id of ActiveForm to use the button with Boolean / String

Installation


The preferred way to install this extension is through composer.

Either run

php composer.phar require demogorgorn/yii2-ajax-submit-button "*"

or add

"demogorgorn/yii2-ajax-submit-button": "*"

to the require section of your composer.json file and run composer update.

yii2-ajax-submit-button's People

Contributors

antonyu avatar cristiantan avatar demogorgorn avatar nafania avatar susgo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

yii2-ajax-submit-button's Issues

Usage not possible with ActiveForm?

I am using an active form based on a model and want to submit this via Ajax. The view code basically looks like this:

        <?php $clubForm = ActiveForm::begin([
            'action' => Url::to(['club/ajax-create']),
        ]); ?>

        <?= $clubForm->field($clubModel, 'name')->textInput(['maxlength' => 150]) ?>

        <?= $clubForm->field($clubModel, 'nation')->dropDownList(
            ArrayHelper::map(Nation::find()->all(), 'id', 'name')
        ) ?>

        <div class="form-group">
            <?php AjaxSubmitButton::begin([
                'label' => 'Speichern',
                'id' => 'saveClubButton',
                'ajaxOptions' => [
                    'type' => 'POST',
                    'url' => Url::to(['club/ajax-create']),
                    'success' => new \yii\web\JsExpression('saveCreatedClub(result)'),
                ],
                'options' => ['class' => 'btn btn-success', 'type' => 'submit'],
            ]);
            AjaxSubmitButton::end();
            ?>
        </div>

        <?php ActiveForm::end(); ?>

However, pressing the button causes the form to perform a POST request, and the page is reloaded, instead if an AJAX request. (Action is the page where the widget is used).

encodeLabels option

hint: add support to encodeLabels, kind regards;

if (isset($item['encodeLabels'])) {
      $this->encodeLabels = $item['encodeLabels'];
}

Render AjaxSubmitButton in Gridview

I am facing problem in rendering AjaxSubmitButton in Gridview.
It should be on location 1 but i comes on location2.

Following is my code.

`[
'format'=>'html',
'value'=> function() {
AjaxSubmitButton::begin([
'label' => 'Check',
'ajaxOptions' => [
'type' => 'POST',
'url' => 'country/getinfo',
/'cache' => false,/
'success' => new \yii\web\JsExpression('function(html){
$("#output").html(html);
}'),
],
'options' => ['type' => 'submit'],
]);
AjaxSubmitButton::end();

    }

],`
untitled

option for confirmation

It would be nice to have an optional confirmation alert before the ajax request is submitted, similar to the trash button in the yii2 grid widget.

No support for file uploads?

Im trying to use it on a form that has file upload widget, all the thing that goes with $_POST are saved, but the $_FILES appear to empty.

Проблема до загрузки

Добрый день, отличная штука, все работает, есть момент - как вызвать событие до отправки данных, то есть как бы показать прелодер, а после загрузки его убрать (убрать знаю как)

Install by Composer Error

"demogorgorn/yii2-ajax-submit-button": "*"
composer gets message: could not to be any version

with "demogorgorn/yii2-ajax-submit-button": "dev-master" composer install yii2-ajax-submit-button normaly.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.