Here is the working solution:
- One form (dropdown) per row in gridview
- 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(...)