DrBorrow
DrBorrow

Reputation: 958

Yii2 activeform ajax

I have inserted an activeform within each row of a GridView as follows:

Gridview element:

    [
        'content' => function($model) {
            return $this->render('_departmentForm',
                [
                    'model' => $model,
                ]);
        },
    ],

The form:

<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<?php $form = ActiveForm::begin(
    ['action' => ['test']]
); ?>

<?= $form
    ->field($model, 'fk_departmentID')
    ->label(false)
    ->dropDownList(
        $model->departments,
        [
            'prompt' => '---- Select Dept ----',
            'onchange' => 'this.form.submit()',
        ]
    ); ?>

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

What I am trying to achieve: When the user changes the dropdown value (i.e. selects a new department for the row), the page should save the new value immediately without refreshing the form.

Unfortunately I don't know what to do next. The form is displaying OK but I don't know how to do an ajax submission.

Thanks!

Upvotes: 2

Views: 1353

Answers (1)

DrBorrow
DrBorrow

Reputation: 958

Here is the working solution:

  1. One form (dropdown) per row in gridview
  2. If user changes the dropdown value, the database is immediately updated via ajax without a page reload

Form: (_departmentForm.php)

<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;

?>
<?php $form = ActiveForm::begin(
    [
        'action' => [
            'survey/department', 
            'question_id' => $model->question_id,
        ],
    ]
); ?>

<?= $form
    ->field($model, 'fk_departmentID')
    ->label(false)
    ->dropDownList(
        $model->departments,
        [
            'prompt' => '-- none --',
            'class' => 'form-control ajax-department',
            //'onchange' => 'this.form.submit()', - used for debugging
        ]
    ); ?>

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

GridView:

<?= GridView::widget([
    'dataProvider' => $questionData,
    'filterModel' => $questionSearch,
    'pager' => [
        'firstPageLabel' => 'First',
        'lastPageLabel' => 'Last',
    ],
    'columns' => [
        //... other fields here
        [
            'content' => function($model) {
                return $this->render('_departmentForm',
                    [
                        'model' => $model,
                    ]);
            },
        ],

    ],
]); ?>

JQuery:

$('.ajax-department').on('change', function () {
    var form = $(this).parent().parent(); // form of the dropdown
    $.ajax({
        url: form.attr('action'),
        type: 'post',
        data: form.serialize(),
        success: function (response) {
            //alert($(response).attr('msg'));
        },
        error: function () {
            alert('Error: There was an error whilst processing this request.');
        }
    });
    return false; 
});

Controller Action:

use yii\web\Response;

public function actionDepartment($question_id)
{
    $model = $this->findModel(['question_id' => $question_id]);
    $post = Yii::$app->request->post();
    Yii::$app->response->format = Response::FORMAT_JSON;

    if ($model->load($post) && $model->save()) {
        return ['msg' => 'Successfully updated'];
    } else {
        return ['msg' => 'Update failed'];
    }
}

That's it - you now have an ajax dropdown within each row of the GridView.

A couple tips: When debugging the action (server-side activity), comment out the jquery function and uncomment the "onchange" parameter in the form. This causes the form to submit on change and allows you to debug the action. Once your action is working, you can comment out the "onchange" action.

When debugging the client-side (jQuery) use console.log(...) or alert(...)

Upvotes: 1

Related Questions