Skip to content

Instantly share code, notes, and snippets.

@jamband
Created May 26, 2015 11:02
Show Gist options
  • Save jamband/cf1ab228a708c5fdcdbc to your computer and use it in GitHub Desktop.
Save jamband/cf1ab228a708c5fdcdbc to your computer and use it in GitHub Desktop.
Yii 2: Ajax + Delete
<?php Pjax::begin(['id' => 'pjax-container']) ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
// ...
[
'class' => 'yii\grid\ActionColumn',
'buttons' => [
'delete' => function ($url) {
return Html::a(Yii::t('yii', 'Delete'), '#', [
'title' => Yii::t('yii', 'Delete'),
'aria-label' => Yii::t('yii', 'Delete'),
'onclick' => "
if (confirm('ok?')) {
$.ajax('$url', {
type: 'POST'
}).done(function(data) {
$.pjax.reload({container: '#pjax-container'});
});
}
return false;
",
]);
},
],
],
],
]); ?>
<?php Pjax::end() ?>
<?php
class PostController extends Controller
{
// ...
public function actionDelete($id)
{
$this->findModel($id)->delete();
if (!Yii::$app->request->isAjax) {
return $this->redirect(['index']);
}
}
}
@tiagomv94
Copy link

nice!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment