Search code examples
yii2pjaxactive-form

Yii2 - checkbox change commit ActiveForm


in the index.php there is a checkbox within a active form

<div class="form-group pull-right" style="margin-right: 10px">
    <?php Pjax::begin(['id' => 'options']); ?>
    <?php $form = ActiveForm::begin(['method' => 'get', 'action' => ['ensemble/index'], 'options' => ['data-pjax' => true]]); ?>

    <?= $form->field($searchModel, 'completed')->checkbox(); ?>
    <?= Html::submitButton('Apply', ['class' => 'btn btn-success']) ?>

    <?php ActiveForm::end(); ?>
    <?php Pjax::end(); ?>
</div>

also there is kartik gridview in the index.php

<?= GridView::widget($gridConfig); ?>

with the following configuration

$gridConfig['pjax'] = true;
$gridConfig['pjaxSettings'] = ['options' => ['id' => 'pjaxGrid']];

the ensemble controller with the index action looks like this

public function actionIndex()
{
    $searchModel = new EnsembleSearch();
    $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

    return $this->render('index', [
        'searchModel' => $searchModel,
        'dataProvider' => $dataProvider,
    ]);
}

This does work every thing just fine. I can check / uncheck the checkbox field and hit the submit button; which then reloads the gridview. Just cool.

Now i was wondering if it is possible, to just make this with only by clicking the checkbox? So if i check / uncheck the checkbox the gridview will be reloaded (pjax'd).

cheers, Luc


Solution

  • Assign id to your form as well as class to your checkbox.

    <div class="form-group pull-right" style="margin-right: 10px">
        <?php Pjax::begin(['id' => 'options']); ?>
        <?php $form = ActiveForm::begin([
                'id' => 'filter-form', 
                'method' => 'get', 
                'action' => ['ensemble/index'], 
                'options' => ['data-pjax' => true]
            ]); ?>
        <?= $form->field($searchModel, 'completed',['class'=>'status_chk'])->checkbox(); ?>
        <?= Html::submitButton('Apply', ['class' => 'btn btn-success']) ?>
        <?php ActiveForm::end(); ?>
        <?php Pjax::end(); ?>
    </div>
    

    Add this script to your index.php file.

    <?php
    $this->registerJs(
       '$("document").ready(function(){ 
            $(document).on("change",".status_chk", function() {
                $("#filter-form").submit();
            });
        });'
    );
    ?>