Created
May 26, 2015 11:02
-
-
Save jamband/cf1ab228a708c5fdcdbc to your computer and use it in GitHub Desktop.
Yii 2: Ajax + Delete
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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() ?> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class PostController extends Controller | |
{ | |
// ... | |
public function actionDelete($id) | |
{ | |
$this->findModel($id)->delete(); | |
if (!Yii::$app->request->isAjax) { | |
return $this->redirect(['index']); | |
} | |
} | |
} |
We can also do this use pjax:
view:
<?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'),
'data-pjax' => 'pjax-container',//pjax
'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'),
'data-method' => 'post',
]);
},
],
],
],
]); ?>
<?php Pjax::end() ?>
controller:
<?php
class PostController extends Controller
{
// ...
public function actionDelete($id)
{
$this->findModel($id)->delete();
$searchModel=new PostSearch();//the model
$url=Yii::$app->request->referrer;//the referer url
$arr = parse_url($url, PHP_URL_QUERY);
parse_str($arr, $output);//get $_GET array
$dataProvider = $searchModel->search($output);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
}
Why this is Hard delete not Soft delete in DB?
Thanks a lot!
nice!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks...