Yii2 : pjax in window popup - php

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

Related

Yii2 - Keep child data in select option from parent dependent dropdown in uclead Tabular Input

I made a tabular input where I would enter several records at once into one table in the database.
I use this extension: https://github.com/unclead/yii2-multiple-input/wiki/Usage#tabular-input
From this extension, I combine it with dependent dropdown.
Here is the code.
public function actionCreateMulti() {
$request = Yii::$app->request;
$models = [new MaterialLocations()];
if ($request->isAjax) {
/**
* Process for ajax request
*/
Yii::$app->response->format = Response::FORMAT_JSON;
if ($request->isGet) {
return [
'title' => "Create new MaterialLocations",
'content' => $this->renderAjax('_form_create_multi', [
'models' => $models,
]),
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::button('Order', ['class' => 'btn btn-primary', 'type' => "submit"])
];
} else if ($eglData = $request->post('MaterialLocations', [])) {
foreach (array_keys($eglData) as $index) {
$models[$index] = new MaterialLocations();
}
if (Model::loadMultiple($models, $request->post()) && ActiveForm::validateMultiple($models)) { // if failed
return [
'title' => "Create new MaterialLocations",
'content' => $this->renderAjax('_form_create_multi', [
'models' => $models,
]),
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::button('Order', ['class' => 'btn btn-primary', 'type' => "submit"])
];
} else { // success
foreach ($models as $single) {
$single->save(false);
}
return [
'forceReload' => '#crud-datatable-pjax',
'title' => "Create new MaterialLocations",
'content' => '<span class="text-success">Create MaterialLocations success</span>',
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::a('Create More', ['create'], ['class' => 'btn btn-primary', 'role' => 'modal-remote'])
];
}
} else {
return [
'title' => "Create new MaterialLocations",
'content' => '<pre>' . VarDumper::dumpAsString($request->post()) . '</pre>',
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::button('Order', ['class' => 'btn btn-primary', 'type' => "submit"])
];
}
} else {
/**
* Process for non-ajax request
*/
new ForbiddenHttpException(); // just for test
}
}
And the following is a view of the tabular input.
<?php $form = ActiveForm::begin(); ?>
<?php try {
echo TabularInput::widget([
'id' => 'some-id',
'models' => $models,
'cloneButton' => true,
'addButtonPosition' => MultipleInput::POS_FOOTER,
'sortable' => true,
'columns' => [
[
'name' => 'cupboard_id',
'title' => $models[0]->getAttributeLabel('cupboard_id'),
'enableError' => true,
'type' => Select2::className(),
'options' => [
'data' => $cupBoards,
'options' => [
'prompt' => '== Choose a vendor ==',
'onChange' => $jsOnChange, // this is handle onChange to find list row
'class' => 'form-control cupboard-id',
]
],
],
[
'name' => 'row',
'title' => $models[0]->getAttributeLabel('row'),
'type' => 'dropDownList',
'items' => [],
'value' => function ($data) {
return $data->row;
},
'options' => [
'class' => 'form-control row-cupboard',
],
'columnOptions' => [
'style' => 'width: 100px;',
]
],
],
]);
} catch (Exception $e) {
echo $e->getMessage();
} ?>
<?php ActiveForm::end(); ?>
As you can see, the first input column is: 'cupboard_id',
If there is onChange, it will generate data for the 'row' column.
<?php
$urlOnChangeCupboard = Url::toRoute(['cupboards/find-row-column-available']);
$jsOnChange = <<<JS
var cupboard = jQuery(this);
var row = cupboard.closest('tr');
var rowCupboard = row.find('.row-cupboard');
var columnCupboard = row.find('.column-cupboard');
jQuery.post('$urlOnChangeCupboard', { id : cupboard.val() }, function(response){
rowCupboard.find('option').remove().end();
columnCupboard.find('option').remove().end();
jQuery.each(response.data.rows, function(index, value){
rowCupboard.append('<option value=' + value + '>' + value + '</option>');
});
});
JS;
?>
<?php
function callBack($cupboardID) {
$data = Cupboards::find()->where(['id' => $cupboardID])->one();
$rowsRaw = range($data->rows_start, $data->rows_amount);
$rows = array_combine($rowsRaw, $rowsRaw);
return $rows;
}
?>
The problem is, when POST (Submit) the data, and then it is validated and there are still errors,
data from the column row should still be based on the cupboard selection.
At this time, after posting, the data from 'row' is empty
Please help.
Fixed with columnOptions closure
[
'name' => 'row',
'title' => $models[0]->getAttributeLabel('row'),
'type' => 'dropDownList',
'items' => function ($model) {
$data = [];
if (isset($model->row)) {
$cupBoards = Cupboards::find()->where(['id' => $model->cupboard_id])->one();
$rowsRaw = range($cupBoards->rows_start, $cupBoards->rows_amount);
$data = array_combine($rowsRaw, $rowsRaw);
}
return $data;
},
'value' => function ($data) {
return $data->row;
},
'options' => [
'class' => 'form-control row-cupboard',
],
'columnOptions' => [
'style' => 'width: 100px;',
]
],

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 Update,View,Delete as per login user in yii2?

I have to change the the id of view,update,delete as per login user but when I click on View I get ID of index.I wanna change a particular company as per id..Please help me I am new in yii2...Thanks in advance.
actionIndex()
$searchModel = new VendorsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->pagination->pageSize = 10;
$user = \Yii::$app->user->identity;
$userid = \Yii::$app->user->identity->id;
$query1 = new \yii\db\Query;
$query1->select('*')->from('vendors')->where(['ven_contact_person_id' => $userid,'deleted' => 'N']);
$query1->createCommand();
$dataProvider1 = new ActiveDataProvider([
'query' => $query1,
'pagination' => false,
]);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'dataProvider1' => $dataProvider1,
]);
index.php
<?= GridView::widget([
'dataProvider' => $dataProvider,
'dataProvider' => $dataProvider1,
'filterModel' => $searchModel,
'columns' => [
'ven_id',
'ven_company_name',
'ven_website',
'ven_contact_no',
'ven_email_id:email',
['class' => 'yii\grid\ActionColumn',
'header' => 'Action',
'template' => '{view} {edit} {delete}',
'buttons' => [
'view' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-eye-open"></span>', $url);
},
'edit' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-pencil"></span>', $url);
},
'delete' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-trash"></span>', $url);
},
],
'urlCreator' => function ($action, $dataProvider, $key, $index) {
if ($action === 'view') {
return Url::to(['vendors/view', 'id' =>$dataProvider['ven_id']]);
}
if ($action === 'edit') {
return Url::to(['/vendors/update', 'id' =>$dataProvider['ven_id']]);
}
if ($action === 'delete') {
return Url::to(['/vendors/delete', 'id' =>$dataProvider['ven_id']]);
}
return $url;
}
],
],
]); ?>
For icon and model->id i think you need this
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
'name',
['class' => 'yii\grid\ActionColumn',
'header' => 'Action',
'template' => '{view} {edit} {delete}',
'buttons' => [
'view' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-eye-open"></span>', $url);
},
'edit' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-pencil"></span>', $url);
},
'delete' => function ($url, $model) {
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',
]);
},
],
'urlCreator' => function ($action, $model, $key, $index) {
if ($action === 'view') {
$url = Url::to(['/yourController/view', 'id' =>$model->id]);
}
if ($action === 'edit') {
$url = Url::to(['/yourController/edit', 'id' =>$model->id]);
}
if ($action === 'delete') {
$url = Url::to(['/yourController/delete', 'id' =>$model->id]);
}
return $url;
}
],
],
]);
sorry for adding a "answer" (coulden't add an comment it requires reputation >= 50)
could you add the index view rendered file ?
in my opinion this will be a mistake in that file for example the method that works for me:
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
'name',
['class' => 'yii\grid\ActionColumn',
'header' => 'Action',
'template' => '{view} {edit} {delete}',
'buttons' => [
'view' => function ($url, $model) {
return Html::a('View', $url);
},
'edit' => function ($url, $model) {
return Html::a('Edit', $url);
},
'delete' => function ($url, $model) {
return Html::a('Delete', $url);
},
],
],
],
]);

Yii2 Pjax Delete not working

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']

how to add bootstrap modal to update action in YII2

I know the below code creates bootstrap modal with ADD button. I want to make this work in update button. And below that is the yii2 action column of index page.
I need to open bootstrap modal when the update button is clicked.
Modal Code
Modal::begin([
'toggleButton' => [
'label' => '<i class="glyphicon glyphicon-plus"></i> Add',
'class' => 'btn btn-success'
],
'closeButton' => [
'label' => 'Close',
'class' => 'btn btn-danger btn-sm pull-right',
],
'size' => 'modal-lg',
]);
$newmodel = new Comment();
echo $this->render('/comment/create', ['model' => $newmodel]);
Modal::end();
Action Column in index page
[
'class' => 'yii\grid\ActionColumn',
'template' => '{view} {update} {delete}',
/* 'buttons'=>[
'view' => function ($url, $comment) {
return Html::a('<span class="glyphicon glyphicon-plus">
</span>',$url,
[
'title' => Yii::t('yii', 'view'),
]);
}
], */
'urlCreator' => function ($action, $dataProvider, $key, $index) {
if ($action === 'view') {
$url = Yii::$app->urlManager->createUrl('option?id='.$key.'');
return $url;
}
if ($action === 'update') {
$url = Yii::$app->urlManager->createUrl('question/update?id='.$key.'');
return $url;
}
if ($action === 'delete') {
$url = Yii::$app->urlManager->createUrl('question/delete?id='.$key.'');
return $url;
}
}
],

Categories