Revision #176 has been created by rackycz on Mar 21, 2020, 2:12:39 AM with the memo:
[...]
You can then use http://myFictiveUrl.local in your browser
**Modal window + ajax**
---
Let's have a GridView (list of users) with edit-button which will open the edit-form in a modal window. Once user-detail is changed, ajax validation will be executed. If something is wrong, the field will be highlighted. If everything is OK and saved, modal window will be closed and the GridView will be updated.
Let's add the button to the GridView in the view **index.php** and let's wrap the GridView into the Pjax
. Also ID is added to the GridView so it can be refreshed later via JS:
```php
<?php yii\widgets\Pjax::begin();?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'id' => 'user-list-GridView',
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'username',
'email:email',
['class' => 'yii\grid\ActionColumn',
'buttons' => [
'user_ajax_update_btn' => function ($url, $model, $key) {
return Html::a ( '<span class="glyphicon glyphicon-share" aria-hidden="true"></span> ',
['user/update', 'id' => $model->id],
['class' => 'openInModal', 'data-modal-titl' => 'Some text']
);
);
},
],
],
'template' => '{update} {view} {delete} {user_ajax_update_btn}'
],
],
]); ?>
<?php yii\widgets\Pjax::end();?>[...]
// This section can be moved to "\views\layouts\main.php"
yii\bootstrap\Modal::begin([
'header' => '<span id="modalTitle">Title</span>',
'id' => 'modalDialog1',
'size' => 'modal-lg',
]);
echo "<div id='modalContent'></div>";[...]
$this->registerJs(
"$('a.openInModal').click(function(e){
e.preventDefault();
$('#modalDialog1 #modalTitle').text('aaa');
$('#modalDialog1').modal('show')
.find('#modalContent')
.load($(this).attr('href'));
return false;
});",
yii\web\View::POS_READY,
'modalHandler'
);
?>[...]
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
if (Yii::$app->request->isAjax) {
return "<script>"
. "$.pjax.reload({container:'#user-list-GridView'});"
. "$('#modalDialog1').modal('hide');"
. "</script>";
}
}
return $this->redirect(['view', 'id' => $model->id]);
}
if (Yii::$app->request->isAjax) {
return $this->renderAjax('update', [
'model' => $model,
]);
}
return $this->render('update', [
'model' => $model,
]);
}
```[...]
<?php $form = ActiveForm::begin([
'id'=>'user-detail-ActiveForm',
'options' => ['data-pjax' => 1 ]
]); ?>
<?= $form->field($model, 'username')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'password')->passwordInput(['maxlength' => true]) ?>[...]