Call Yii2 Pjax GridView Button

I am trying to create an Ajax GridView using Pjax. Everything works fine, except that the view, update, and delete buttons are not AJAX. Code:

<?php yii\widgets\Pjax::begin(['id' => 'demo']); ?> <?= GridView::widget([ 'dataProvider' => $dataProvider, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], 'id', 'name', ['class' => 'yii\grid\ActionColumn'], ], ]); ?> <?php yii\widgets\Pjax::end(); ?> 

The problem is that links for deleting, viewing, and updating have the data-pjax = 0 attribute, which disables AJAX functionality. I canโ€™t find out how to set it also data-pjax = 1.

+2
source share
1 answer

You should do as below:

To delete an action

1- Change the delete action as shown below:

 public function actionDelete($id) { $this->findModel($id)->delete(); if (Yii::$app->getRequest()->isAjax) { $dataProvider = new ActiveDataProvider([ 'query' => ModelName::find(), 'sort' => false ]); return $this->renderPartial('index', [ 'dataProvider' => $dataProvider ]); } return $this->redirect(['index']); } 

2- As grid:

 ['class' => 'yii\grid\ActionColumn', 'buttons' => [ 'delete' => function ($url, $model) { return Html::a('<span class="glyphicon glyphicon-trash"></span>', $url, [ 'title' => Yii::t('yii', 'Delete'), 'data-pjax'=>'w0', ]); } ] ], 

Now it works with Pjax .

Notes

  • My code in deleteAction() can slow performance. You can write your own.
  • w0 usually the default identifier for Pjax . You can add id to Pjax and write there.
  • This is the same for Update and View , but you need to change the way the Update and View views are displayed.
  • It is strongly recommended that you read the PJax Yii2 : http://www.yiiframework.com/doc-2.0/yii-widgets-pjax.html
+5
source

Source: https://habr.com/ru/post/989702/


All Articles