Yii2 Pjax Delete not working - php

I am trying to make an Ajax GridView using Pjax with delete button. Deleting goes with no Ajax. I am new to Yii2 so any help would be appreciated. Thank you.
index.php
<?php Pjax::begin(['id' => 'countries']) ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'title',
['class' => 'yii\grid\ActionColumn',
'buttons' => [
'delete' => function ($url, $model, $key) {
return Html::a('<span class="glyphicon glyphicon-trash"></span>', $url, [
'title' => Yii::t('yii', 'Delete'),
'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'),
'data-method' => 'post',
]);
},
]
],
],
]); ?>
<?php Pjax::end() ?>
Controller
public function actionDelete($id)
{
$model = new Category();
$this->findModel($id)->delete();
$dataProvider = new ActiveDataProvider([
'query' => Category::find(),
]);
return $this->render('index', [
'dataProvider' => $dataProvider,
'model' => $model,
]);
}
This is public function actionIndex() in the Controller
public function actionIndex()
{
$model = new Category();
$dataProvider = new ActiveDataProvider([
'query' => Category::find(),
]);
if ($model->load(Yii::$app->request->post()) && $model->save())
{
$model = new Category();
}
return $this->render('index', [
'dataProvider' => $dataProvider,
'model' => $model,
]);
}

data-method and data-confirm don't let you create ajax request via pjax, you should implements your own confirmation dialog and drop POST verb filter, or you can implements your own ajax plugin with confirmation dialog and specifying http method.
Also, i think, there must be way to extend pjax plugin by confirmation dialog, but Yii2 don't provide this by default.

first of all remove 'data-confirm' and 'data-method' => 'post'. pjax not going to work.
If you want to implement a confirm box with action button, here is what I would do in my view index.php file ..
<?php Pjax::begin(['id' => 'pjax-container']);
echo GridView::widget([
'test' => function ($url, $dataProvider) {
return Html::a('Test',
['/site/test'],
['title'=>'Test',
'onclick' => "if (confirm('ok?')) {
$.ajax('/site/test', {
type: 'POST'
}).done(function(data) {
$.pjax.reload({container: '#pjax-container'});
});
}
return false;
",
]);
},
])
Pjax::end();
?>
and in my controller
public function actionTest()
{
if (!Yii::$app->request->isAjax) {
return $this->redirect(['index']);
}
}
This way you would have confirmation etc. as well. If you want you may use other third party bootstrap confirmation etc. and will work fine.

<?php Pjax::begin(['id' => 'model-grid']);
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
//...
[
'class' => 'yii\grid\ActionColumn',
'template' => '{update} {delete}',
'contentOptions' => ['class' => 'action-column'],
'buttons' => [
'delete' => function ($url, $model, $key) {
return Html::a('<span class="glyphicon glyphicon-trash"></span>', $url, [
'title' => 'Delete',
'data-pjax' => '#model-grid',
]);
},
],
],
],
]);
Pjax::end(); ?>
In controller
public function actionDelete($id)
{
$this->findModel($id)->delete();
$searchModel = new ModelSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}

Please try modify actionDelete()
public function actionDelete($id)
{
$this->findModel($id)->delete();
return \yii\web\Response::redirect(['index'] , 302 , false);
// return $this->redirect(['index']);
}
because Controller->redirect() can not disable ajaxCheck , you need use Response to do this.
I have create the same issue in https://github.com/yiisoft/yii2/issues/11058.

Can use like this:
in view:
'delete' => function ($url, $model, $key) {
$options = [
'title' => Yii::t('common', 'delete'),
'aria-label' => Yii::t('common', 'delete'),
'data-pjax' => 'w0',//id
'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'),
'data-method' => 'post',
'class' => 'btn btn-xs btn-danger'
];
return Html:: a('<i class="fa fa-fw fa-trash"></i>', [
'delete',
'id' => $model -> id
], $options);
}
in controller:
$this -> findModel($id) -> delete ();
$searchModel = new AdminSearch();
//get the referer url
$url = Yii::$app -> request -> referrer;
$arr = parse_url($url, PHP_URL_QUERY);
parse_str($arr, $output);//get the $_GET array
$dataProvider = $searchModel -> search($output);
return $this -> render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);

First add Pjax::end(); at end of the gridview
then specify:
'delete' => function ($url, $model, $key)
{
return Html::a('<span class="glyphicon glyphicon-trash"></span>', $url, [
'title' => Yii::t('yii', 'Delete'),
'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'),
'data-method' => 'post',
]);
},
Note that you don't need to specify 'data-pjax' => '0' because it disables the pjax link.
For more details check this link
Your controller should be:
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}

Don't set data-method and data-confirm because Pjax not supported that.
After removing both still not workign,yes because of below code of your controler does not allow Pjax get Request.
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'], // **remove this**
],
],
];
You need to use Pjax Post Method
Apply this in Your Pjax
'clientOptions' => ['method' => 'POST']

Related

How to display gridview row to particular view?

This is my grid :
I made a query and created a dataprovider to view in a gridview, and now I want to view each row in a particular view. How do I get all line data to send when clicking preview?
on my controller
$model = new Aviso();
if ($model->load(Yii::$app->request->post())) {
$seg = $model->seguradora;
$seguradora = SeguradoraSearch::getNomeSeg($seg);
$query = new Query;
$query->select(['apolice_idapolice','nome','email', 'contacto','premio','data_final','situacao'])
->from('seguro')
->innerJoin('cliente', 'cliente_idcliente = idcliente')
->where(['between','data_final' ,$model->data_inicio,$model->data_final])
->andWhere(['situacao'=> "Pendente"])
->andWhere(['seguradora_idseguradora'=>$seg]);
$dataAviso = new ActiveDataProvider([
'query' => $query,
]);
return $this->render('index',[
'dataProvider' => $dataAviso,'segName'=>$seguradora,
]);
}
return $this->render('create', [
'model' => $model,
]);
}
On My index
<?= GridView::widget([
'dataProvider' => $dataProvider,
'summary' => '',
'columns' => [
['class' => 'yii\grid\SerialColumn'],
['attribute'=>'nome',
'label'=> 'Cliente',
],
['attribute'=>'email',
'label'=> 'E-mail',
],
['attribute'=>'apolice_idapolice',
'label'=> 'Apolice',
],
'contacto',
['attribute'=>'premio',
'format' => ['decimal', 2],
'label'=> 'Valor (Mts)',
],
'data_final',
['attribute'=>'situacao',
'label'=> 'Situação',
],
['class' => 'yii\grid\ActionColumn', 'template' => '{view}','header' => 'visualizar' ],
],
]); ?>
<?php Pjax::end(); ?>
I wamt to click on the icon visualizar and render on particular view.
You could configure the ActionColumn in proper way using template and urlCreator
assuming $model->id is you target id for the view
['class' => 'yii\grid\ActionColumn',
'template' => '{view}',
'urlCreator' => function ($action, $model, $key, $index) {
if ($action === 'view') {
return \yii\helpers\Url::to(['your-controller/your-action', 'id' => $model->id]);
}
}
],

Updating forms values is not working yii2

I have default forms which were generated by crud. I need to update message column.
My View site/index.php
<div class="notifications-events-index">
<?= Html::encode($this->title) ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'summary' => false,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'date_at',
'type',
'event_id',
[
'attribute' => 'Message',
'filter' => true,
'format' => 'raw',
'value' => function ($model) {
$form = ActiveForm::begin([
'action' => Yii::$app->urlManager->createUrl(['site/update', 'id' => $model->id])
]);
return $this->render('_msg', [
'model' => $model,
'form' => $form,
]);
},
]
],
]); ?>
<?php ActiveForm::end(); ?>
My updateAction in SiteController
public function actionUpdate($id)
{
$model = $this->findModel($id);
$dataProvider = new ActiveDataProvider([
'query' => NotificationsEvents::find()->orderBy('date_at'),
]);
if ($model->load(Yii::$app->request->post())) {
$model->save(false);
return $this->redirect(['index']);
}
return $this->render('index', [
'dataProvider' => $dataProvider,
'model' => $model,
]);
}
findModel is working. When I save my updating values they are not updating. Any ideas?
Possible Reason to not updating the records:
Check validation , there may be a chance some validation is applying.
Check you attribute available in safe in your model .
Debug Your POST data. There may be a chance your post data is not posted .
If you still not able to solve it please post you model as well .

How to hide rows on condition from GridView?

$query =Cms::find();
$dataProvider = new ActiveDataProvider([
'query' => $query ,
]);
Hi, I'm trying to hide certain rows whose 'Status_id' is set to 'Inactive' which is done using a custom action button I've created in the Actions column. I figured I might be able to do it if I could add my own query in the $dataprovider but I don't know how to do that too. Please help if it's the right way and if not how to do I do it? Thanks in advance.Here's my widget.
echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
'Contract_id',
'Status_id',
['header' => 'Actions',
'class' => 'yii\grid\ActionColumn',
'template' => '{new_action}',
'buttons' => [
'new_action' => function ($url) {
return Html::a('<span class="glyphicon glyphicon-fire"></span>', $url, [
'title' => Yii::t('app', 'Burn Contract'),
'data-confirm' => Yii::t('yii', 'Are you sure you want to burn this contract?'),
'data-method' => 'post', 'data-pjax' => '0',
]);
}
], 'urlCreator' => function ($action, $model) {
if ($action === 'new_action') {
$url = Url::to(['cms/burn', 'id' => $model->Contract_id]);
return $url;
}
}
],
],
]);
i think this may work:
echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
'Contract_id',
'Status_id',
['header' => 'Actions',
'class' => 'yii\grid\ActionColumn',
'template' => '{new_action}',
'buttons' => [
'new_action' => function ($url) {
return Html::a('<span class="glyphicon glyphicon-fire"></span>', $url, [
'title' => Yii::t('app', 'Burn Contract'),
'data-confirm' => Yii::t('yii', 'Are you sure you want to burn this contract?'),
'data-method' => 'post', 'data-pjax' => '0',
]);
}
], 'urlCreator' => function ($action, $model) {
if ($action === 'new_action') {
$url = Url::to(['cms/burn', 'id' => $model->Contract_id,'burn'=>true]);
return $url;
}
}
],
],
]);
controller:
$query =Cms::find();
if (\Yii::$app->request->post('burn'))
{
$query->where(['<>','Status_id', 'Inactive']);
}
$dataProvider = new ActiveDataProvider([
'query' => $query
]);

How to open view page in popup in yii2?

I have to open view page contain in popup instead of page.After click on view open view contain in popup yii2
You should try this code for opening popup. and also you need to render with ajax view using this $this->renderAjax().
controller
public function actionView($id)
{
if (Yii::$app->request->isAjax) {
return $this->renderAjax('view', [
'model' => $this->findModel($id),
]);
} else {
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
}
View
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
...................
[
'class' => 'yii\grid\ActionColumn',
'buttons' => [
'view' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-eye-open"></span>', $url , ['class' => 'view', 'data-pjax' => '0']);
},
],
....................
]);
$this->registerJs(
"$(document).on('ready pjax:success', function() { // 'pjax:success' use if you have used pjax
$('.view').click(function(e){
e.preventDefault();
$('#pModal').modal('show')
.find('.modal-content')
.load($(this).attr('href'));
});
});
");
yii\bootstrap\Modal::begin([
'id'=>'pModal',
]);
yii\bootstrap\Modal::end();
?>

Yii2 : pjax in window popup

first, sorry for my english...
i have a CRUD in window popup, but i can't update the grid in ajax success (insert, update and delete) without refresh page and closes modal.
In success ajax:
}).done(function(data) {
$('#div-form').html(data.form);
if(data.success){
$.pjax.reload({container:'#pjax-resposta-possivel'});
}
})
In action controller:
public function actionSalvarRespostaPossivel()
{
$return = [
'success' => false,
'form' => null
];
Yii::$app->response->format = Response::FORMAT_JSON;
$post = Yii::$app->request->post();
if ($post && $post['RespostaPossivelDetalhes']['id']) {
$model = RespostaPossivelDetalhes::findOne([
$post['RespostaPossivelDetalhes']['id']
]);
} else {
$model = new RespostaPossivelDetalhes();
}
if ($model->load($post) && $model->save()) {
$return['success'] = true;
$tblcacd_id = $model->tblcacd_id;
$model = new RespostaPossivelDetalhes();
$model->tblcacd_id = $tblcacd_id;
}
$return['form'] = $this->renderPartial('_formRespostaPossivel', [
'model' => $model
]);
return $return;
}
In view:
<?php Pjax::begin(['enablePushState' => false, 'id' => 'pjax-resposta-possivel'])?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'emptyCell' => ' ',
'summary' => "Exibindo {begin} - {end} de {totalCount}.",
'layout' => "{pager}\n{items}\n{summary}",
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'chave',
'desc_resposta',
[
'class' => 'yii\grid\ActionColumn',
'template' => '{update} {delete}',
'contentOptions'=>['style'=>'width: 10%;text-align:center;'],
'buttons' => [
'update' => function ($url, $model)
{
return Html::a('<span class="glyphicon glyphicon-pencil"></span>', false, [
'data-id' => $model->id,
'class' => 'btn-update-resposta',
'style' => 'cursor:pointer;'
]);
},
'delete' => function ($url, $model)
{
return Html::a('<span class="glyphicon glyphicon-trash"></span>', false, [
'data-id' => $model->id,
'class' => 'btn-delete-resposta',
'style' => 'cursor:pointer;'
]);
}
]
],
],
]); ?>
<?php Pjax::end(); ?>
I can just update the grid without closing the modal ?
Thanks

Categories