Yii2 Gridview data not changing in Pjax - yii2

Hello i am performing search using pjax in yii2 . I am following this link.
Above link in given for submit which is working fine, but i want to perform on change of slider.
Here is screenshort of my form .
index.php
<div class="bank-index">
<?php echo $this->render('_search', ['model' => $searchModel]); ?>
<?php \yii\widgets\Pjax::begin(); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'bank_name',
'state',
'district',
'city',
'branch',
'time',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
_search.php
<div class="bank-search">
<?php Pjax::begin(['id' => 'Pjax_bank_id']); ?>
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'id') ?>
<?= $form->field($model, 'bank_name') ?>
<?= $form->field($model, 'state') ?>
<?= $form->field($model, 'district') ?>
<?= $form->field($model, 'city') ?>
<?=
$form->field($model, 'time')->widget(Slider::classname(), [
'pluginOptions'=>[
'min'=>0,
'max'=>20,
'step'=>1
]
]);
?>
<?php // echo $form->field($model, 'branch') ?>
<div class="form-group">
<?= Html::submitButton(Yii::t('app', 'Search'), ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton(Yii::t('app', 'Reset'), ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
**How i have registered js file**
registerJs($this->render('searchJs.php')); ?>
searchJs.php
$('#banksearch-time').on('slideStop', function(){
alert('hello');
var form = $(this);
if(form.find('.has-error').length) {
return false;
}
$.ajax({
url: form.attr('action'),
type: 'post',
data: form.serialize(),
success: function(response) {
var csrf = yii.getCsrfToken();
var bank_name = $('#banksearch-bank_name').val();
var state = $('#banksearch-state').val();
var district = $('#banksearch-district').val();
var city = $('#banksearch-city').val();
var time = $('#banksearch-time').val();
var url = 'index'+ '&_csrf='+csrf+'&BankSearch[bank_name]='+bank_name+'&BankSearch[state]='+state+'&BankSearch[district]='+district
+'&BankSearch[city]='+city +'&BankSearch[time]='+time;
$.pjax.reload({url: url, container:'#Pjax_bank_id'});
}
});
}).on('submit', function(e){
e.preventDefault();
});

Solved The problem was I have not assigned the id to Pjax in gridview.<?php yii\widgets\Pjax::begin(['id' => 'gridresult']) ?>
I have assigned Pjax id of _search .php.
I changed From: $.pjax.reload({url: url, container:'#gridresult'});
TO: $.pjax.reload({url: url, container:'#gridresult'});

Good you solved the problem. Here is the another approach. Someone might find this helpful:
$url = \Yii::$app->getUrlManager()->createUrl('bank/index');
<?= $form->field($model, 'time')->widget(Slider::classname(), [
'pluginOptions'=>[
'min'=>0,
'max'=>20,
'step'=>1
],
'pluginEvents' => [
"slideStop" => "function() { refreshGridview($(this).val())}",
]
]); ?>
$js1 = <<<JS
function refreshGridview(value)
{
$.ajax({
url: "$url",
type: 'post',
data: { "BankSearch[id]": value, },
success: function(response) {
var csrf = yii.getCsrfToken();
var bank_id = value;
$.pjax.reload({
url: "$url",
method: 'POST',
data: {
_csrf: csrf,
"BankSearch[id]": value,
},
container:'#bank'
});
}
});
}
JS;
$this->registerJs($js1);
On slidestop plugin event call the custom function with the current value of slider and then through Pjax update the gridview.

Related

Modal Form not work in Yii2 with AdminLTE

I built a web app using Yii2 with adminLTE theme. i'm trying to make modal form in my web app, I've tried in Yii2 without adminLTE it work fine like this:
I did the same way in Yii2 with adminLTE it failed, when I clicked the button, it didn't do anything, and I tried to do inspectElement and I got this:
This is my view in index.php:
<?php
use yii\helpers\Html;
use kartik\detail\DetailView;
use kartik\grid\GridView;
use yii\helpers\Url;
use yii\bootstrap\Modal;
/* #var $this yii\web\View */
/* #var $modelTrip backend\models\TripsSchedule */
\yii\web\YiiAsset::register($this);
?>
<p>
<?= Html::button('Add Schedule', ['value' => Url::to('/intra/admin/bus-passengers/create'), 'class' => 'btn btn-success', 'id' => 'modalButton']) ?>
</p>
<?php
Modal::begin([
'header' => '<h4>Add Passenger</h4>',
'id' => 'modal',
'size' => 'modal-lg',
]);
echo "<div id='modalContent'><div>";
Modal::end();
?>
<div>
<?=
DetailView::widget([
'model' => $modelTrip,
'id' => $modelTrip->tripScheduleId,
'responsive' => true,
'enableEditMode' => false,
'condensed' => true,
'hover' => true,
'mode' => DetailView::MODE_VIEW,
'mainTemplate' => '{detail}',
'attributes' => [
[
'attribute' => 'departureTime',
'label' => 'Departure Time',
'value' => function ($form, $widget) {
$model = $widget->model;
return date('H:i', strtotime($model->departureTime)) . ' WIB';
},
],
],
])
?>
</div>
This is code in controller:
public function actionCreate()
{
$model = new BusPassengers();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->busPassengerId]);
}
return $this->renderAjax('create', [
'model' => $model,
]);
}
You can see, it didn't render anything. Do I need add another additional code because I'm using adminLTE?
Update
Here is the js:
$(function () {
$('#modalButton').click(function () {
$('#modal').modal('show')
.find('#modalContent')
.load($(this).attr('value'));
});
});
Update
Here is the view source and console screenshot
This line is not needed if you already have a layout file, so please remove this
\yii\web\YiiAsset::register($this);
also please make sure jquery file loaded before your js code else it will not work since bootstrap modal is depend on jQuery (please check your console).
Or at the end, your can add js code as Yii way:
<?php
$script = <<< JS
$('#modalButton').click(function () {
$('#modal').modal('show')
.find('#modalContent')
.load($(this).attr('value'));
});
JS;
$this->registerJs($script);
?>
Let me know if it work or please post screenshot of viewSource and console.
Thank you
Update
Try replace these code block and it will work:
1. JS
<script type="text/javascript">
function showModal() {
$('#passenger_modal').modal('show');
$('#passenger_modal_content').load("<?=Yii::getAlias('#web')?>/intra/admin/bus-passengers/create");
}
</script>
2. BUTTON
<p>
<?= Html::button('Add Schedule', ['class' => 'btn btn-success', 'onClick'=>'showModal()']) ?>
</p>
3. MODAL BLOCK
<?php
Modal::begin([
'header' => '<h4>Add Passenger</h4>',
'id' => 'passenger_modal',
'size' => 'modal-lg',
]);
echo '<div id="passenger_modal_content"><div>';
Modal::end();
?>
I just change the id's of blocks but that is not matter at all.
this updated version worked for me problem was my layout footer was hidden and being shown with modal body with this question solution
Yii2 and adminlte : 2.4.13
<?php
Modal::begin([
'header' => '<h4><i class="fa fa-book" style="padding-right:5px"></i>' .
$model->name
. '</h3>',
'id' => 'modal',
'size' => 'modal-lg',
]);
?>
<?= "<div id='modalContent'>" ?>
<?php
$form = ActiveForm::begin(); ?>
<div class="box box-info">
<div class="box-body">
<div class="form-group">
<?= $form->field($chapter, 'name')->textInput() ?>
</div>
<div class="form-group">
<?= $form->field($chapter, 'book_id')->hiddenInput(['value' => $model->id])->label(false); ?>
</div>
<div class="form-group">
<?= $form->field($chapter, 'description')->textarea(['rows' => '6']) ?>
</div>
</div>
<div class="box-footer">
<?= Html::a('Cancel', ['index'], ['class' => 'btn btn-default']) ?>
<?= Html::submitButton('Save', ['class' => 'btn btn-info pull-right']) ?>
</div>
</div>
<?php ActiveForm::end();
Modal::end();
?>
" ?>
<script>
$(function() {
$('#modalButton').click(function() {
$('#modal').modal('show')
.find('#modalContent')
.load($(this).attr('value'));
});
});
</script>

yii2: js calulation in server side

This is a page for calculate the product order.
My mentor told me that:
"The code put the code calculation logic inside JavaScript which means, user can simply inject and modified the content and get discount to make it safe, may either do a recalculation on submit at server side before display, or make the js function to call API, and return the result instead of put calculation logic inside JS"
But I really can't get it, how can I make it in server side?
views:
<?php $form = ActiveForm::begin([
'action'=>['summary'],
'id'=>'order-form',
]); ?>
<?= Html::dropDownList('country', null,['malaysia'=>'Malaysia','singapore'=>'Singapore', 'brunei'=>'Brunei'],['id'=>'country']) ?>
<?= Html::textInput('code','',['class'=>'form-control','placeholder'=>'promotion code','id'=>'code', 'style'=>'text-transform:uppercase'])?>
<?= Html::button('Apply', ['class' => 'btn btn-primary', 'id'=>'apply']) ?>
<?= Html::hiddenInput('id', $model->id) ?>
<?= Html::hiddenInput('discount', '', ['id'=>'discount']) ?>
<?= Html::hiddenInput('ship','',['id'=>'ship']) ?>
<?= Html::hiddenInput('qty', $qty, ['id'=>'qty']) ?>
<?= Html::hiddenInput('subtotal', $subtotal, ['id'=>'subtotal']) ?>
<?= Html::submitButton('Checkout', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
js:
$(document).ready(function() {
var qty=$('#qty').val();
var subtotal=$('#subtotal').val();
$('#discount').val(0);
$("#apply").click(function() {
var code=$('#code').val().toUpperCase();
var off5=(subtotal*0.05).toFixed(2);
var off15=15;
if(code=='OFF5PC'){
if (qty>=2)
$('#discount').val(off5);
else{
$('#discount').val(0);
alert('At least 2 quantities');
}
}
else if(code=='GIVEME15'){
if(subtotal>=100)
$('#discount').val(off15);
else{
$('#discount').val(0);
alert('Minumum puchase of RM100');
}
}
else{
$('#discount').val(0);
alert('Invalid promotion code');
}
if ($('#discount').val()=='0'){
$('#code').val('');
}
});
if(qty>=2||subtotal>=150){
$('#ship').val(0);
$('#shipping').html('0');
}
else{
$('#ship').val(10);
$('#shipping').html('10');
}
$("#country").change(function() {
var country=$('#country').val();
if(country=='malaysia'){
if(qty>=2||subtotal>=150){
$('#ship').val(0);
$('#shipping').html('0');
}
else{
$('#ship').val(10);
$('#shipping').html('10');
}
}
else if(country=='singapore'){
if(subtotal>=300){
$('#ship').val(0);
$('#shipping').html('0');
}
else{
$('#ship').val(20);
$('#shipping').html('20');
}
}
else if(country=='brunei') {
if(subtotal>=300){
$('#ship').val(0);
$('#shipping').html('0');
}
else{
$('#ship').val(25);
$('#shipping').html('25');
}
}
});
});
controllers:
public function actionSummary()
{
$id=Yii::$app->request->post('id');
$qty=Yii::$app->request->post('qty');
$discount=Yii::$app->request->post('discount');
$shipping=Yii::$app->request->post('ship');
$subtotal=Yii::$app->request->post('subtotal');
$area=Yii::$app->request->post('country');
$code=Yii::$app->request->post('code');
$summary=Products::findOne($id);
return $this->render('summary', [
'model' => $summary,
'quantity'=>$qty,
'discount'=>$discount,
'shipping'=>$shipping,
'subtotal'=>$subtotal,
'area'=>$area,
'code'=>$code,
]);
}
use browser tools inspect to determine your id of each fields. Usually the default id in Yii2 begins with view_name combine with "-" and field name.
For validating the form onsubmit, you can enable ajaxvalidation in your form like below.
View:
<?php $form = ActiveForm::begin([
'action'=>['summary'],
'enableAjaxValidation' => true,
'id'=>'order-form',
]); ?>
<?= $form->field($model, 'country')->dropDownList(['malaysia'=>'Malaysia','singapore'=>'Singapore', 'brunei'=>'Brunei']) ?>
<?= $form->field($model, 'code', ['options' => ['class' => 'form-control', 'id'=>'code']])->textInput(['placeholder'=>'promotion code'])?>
<?= Html::button('Apply', ['class' => 'btn btn-primary', 'id'=>'apply']) ?>
<?= Html::hiddenInput('id', $model->id) ?>
<?= Html::hiddenInput('discount', '', ['id'=>'discount']) ?>
<?= Html::hiddenInput('ship','',['id'=>'ship']) ?>
<?= Html::hiddenInput('qty', $qty, ['id'=>'qty']) ?>
<?= Html::hiddenInput('subtotal', $subtotal, ['id'=>'subtotal']) ?>
<?= Html::submitButton('Checkout', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
In your controller file, please add the ajax validation code in your controller before inserting into database. Below is the example ajax validation code for validating from server side.
Controller:
public function actionYourActionName(){
$model = new YourModelClass();
if ($model->load(Yii::$app->request->post())) {
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = yii\web\Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
if($model->save())){
//after successful save if you want to do any thing those codes will goes here.
}
}
return $this->render('your-view-file-name', ['model' => $model]);
}
Model:
<?php
namespace app\models;
use yii;
use yii\db\ActiveRecord;
class YourModelClass extends ActiveRecord
{
...
public function rules(){
return [
[['id', 'discount', 'ship', 'qty', 'subtotal'], 'safe'],
[['country', 'code'], 'required']
];
...
}
?>

Yii2 different form fields on create and on update scenario

In my Model I have created different scenarios. I have one form which is rendered bu both create and update method. The form fields are as follows
Form.php
<?php $form = ActiveForm::begin(); ?>
<?= $form->errorSummary($model, $options = ['header'=>'', 'class'=>'pull-left errorDiv']); ?>
<?= $form->field($model, 'user_fname')->textInput(['class'=>'form-control']);?>
<?= $form->field($model, 'user_lname')->textInput(['class'=>'form-control']); ?>
<?= $form->field($model,'user_email')->textInput(['class'=>'form-control']); ?>
<?= $form->field($model, 'user_password_hash')->passwordInput([]); ?>
<?= $form->field($model, 'user_password_hash_repeat')->passwordInput(['class'=>'form-control']); ?>
<?php $items = ArrayHelper::map(SimAuthAssignment::find()->all(),'item_name' ,'item_name');?>
<?= $form->field($mode, 'item_name')->dropDownList($items,[]);?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
On using update scenario I want only my email, firstname and last name to be rendered from the form.
const SCENARIO_REGISTER = 'signup';
const SCENARIO_CREATE = 'create';
const SCENARIO_UPDATE = 'update';
public function scenarios()
{
return [
self::SCENARIO_REGISTER => ['user_email', 'user_password_hash', 'user_fname', 'user_lname', 'agree','!user_password_hash_repeat','required'],
self::SCENARIO_CREATE => ['user_email', 'user_password_hash', 'user_fname', 'user_lname','!user_password_hash_repeat','required'],
self::SCENARIO_UPDATE => ['user_email', 'user_fname', 'user_lname', 'required'],
];
}
public static function tableName()
{
return 'sim_user';
}
And in my controller update method I am using scenario as below code.
public function actionUpdate($id)
{
$model = $this->findModel($id);
$model->scenario = SimUser::SCENARIO_UPDATE;
// var_dump($model->scenario); exit();
$mode = \app\modules\auth\models\SimAuthAssignment::find()->where(['user_id' => $id])->one();
if ($model->load(Yii::$app->request->post())&& $mode->load(Yii::$app->request->post())) {
$model->save();
return $this->redirect(['view', 'id' => $model->user_id]);
} else {
return $this->renderAjax('update', [
'model' => $model,
'mode' => $mode,
]);
}
}
I want to get only the email, firstname and lastname form fields to be rendered in the form when I edit. I want to ignore the others fields in the form when I edit. What am I missing here? Thanks!!
You are using an activeForm with all the inputField .. so all the fields are submit .. if you want only email, firstname and lastname
you should use another view with onnly these fields
<?php $form = ActiveForm::begin(); ?>
<?= $form->errorSummary($model, $options = ['header'=>'', 'class'=>'pull-left errorDiv']); ?>
<?= $form->field($model, 'user_fname')->textInput(['class'=>'form-control']);?>
<?= $form->field($model, 'user_lname')->textInput(['class'=>'form-control']); ?>
<?= $form->field($model,'user_email')->textInput(['class'=>'form-control']); ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
The scenario then check only the fields you have ruled and the submit return only the data you need
You can use the $model->isNewRecord functionality
if(!$model->isNewRecord) {
echo $form->field('Your-field')->textInput(['class' => 'form-control');
}
If I got you right you want to hide some input elements depends on your form scenario.
So, this can be easily achieved using the following code:
<?php if ($model->isUpdating()) { ?>
<?= $form->field($model, 'user_fname')->textInput(['class' => 'form-control']); ?>
<?= $form->field($model, 'user_lname')->textInput(['class' => 'form-control']); ?>
<?= $form->field($model, 'user_email')->textInput(['class' => 'form-control']); ?>
<?php } ?>
<?php if ($model->isRegistration()) { ?>
<?= $form->field($model, 'user_password_hash')->passwordInput([]); ?>
<?= $form->field($model, 'user_password_hash_repeat')->passwordInput(['class' => 'form-control']); ?>
<?php $items = ArrayHelper::map(SimAuthAssignment::find()->all(), 'item_name', 'item_name'); ?>
<?= $form->field($mode, 'item_name')->dropDownList($items, []); ?>
<?php } ?>
According to this, add the following code to the form model:
public function isUpdating() : bool {
return $this->scenario === self::SCENARIO_REGISTER;
}
public function isRegistration() : bool {
return $this->scenario === self::SCENARIO_UPDATE;
}

Yii2 Pjax on ActiveForm and GridView [ Got it Working]

I have a gridview
<?php Pjax::begin(['id' => 'members']) ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
// 'filterModel' => $searchModel,
'columns' => [
['header'=>'Remove Member',
'value'=> function($data)
{
return Html::a(Yii::t('app', ' {modelClass}', [
'modelClass' =>'',
]), ['members/stl_remove','id'=>$data->id],
['class' => 'btn btn-link fa fa-times fa-2x pop']
);
},
'format' => 'raw'
],
['class' => 'yii\grid\ActionColumn','template'=>'{update}'],
],
]); ?>
<?php Pjax::end() ?>
when i click on the Remove members link a modal popsup (delete.php)
<?php Pjax::begin(['id' => 'delete_members']) ?>
<?php $form = ActiveForm::begin(['options' => ['data-pjax' => true ]]); ?>
<div class="row">
<div class="col-md-5">
<?php echo $form->field($model, 'remarks')->dropDownList(['death' => 'Death',
'marriage' => 'Marriage', 'house_shift' => 'House Shift'],['prompt'=>'Select'])
->label("Reason For Removal"); ?>
</div>
</div>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Remove') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
<?php yii\widgets\Pjax::end() ?>
Now these are my controller code
[code]
public function actionStl_remove($id,$ajax=0)
{
$model = $this->findModel($id);
$model_delete = new Members();
$model->scenario = "remove";
if ($model_delete->load(Yii::$app->request->post()))
{
$model->remarks = $model_delete->remarks;
$model->status = 1;
$model->save();
// $model = new Members();
// return $this->redirect(['index']);
}
else
{
return $this->renderAjax('delete', [
'model' => $model_delete,
'id' => $id,
]);
}
}
I am not able to get data loaded into gridview. I click on the link modal popsup then i submit after that i go on to the index page and the page reloads
This is how i got it working. In delete.php i made following changes.
<?php $form = ActiveForm::begin([
'options' => ['data-pjax' => true,
'id'=> 'dynamic-form111',
// 'validationUrl' => 'validation-rul'
]]); ?>
<div class="row">
<div class="col-md-5">
<?php echo $form->field($model, 'remarks')->dropDownList(['death' => 'Death',
'marriage' => 'Marriage', 'house_shift' => 'House Shift'],['prompt'=>'Select'])
->label("Reason For Removal"); ?>
</div>
</div>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Remove') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
basically i gave an id to the from dynamic-form111.
Then in index.php along with gridview in pjax i added the below code
<?php
$this->registerJs(
'jQuery(document).ready(function($){
$(document).ready(function () {
$("body").on("beforeSubmit", "form#dynamic-form111", function () {
var form = $(this);
// return false if form still have some validation errors
if (form.find(".has-error").length)
{
return false;
}
// submit form
$.ajax({
url : form.attr("action"),
type : "post",
data : form.serialize(),
success: function (response)
{
$("#ajaxModal").modal("toggle");
$.pjax.reload({container:"#countries"}); //for pjax update
},
error : function ()
{
console.log("internal server error");
}
});
return false;
});
});
});'
);
?>
which via ajax check if delete.php has been submitted successfully if yes then reloads gridview using pjax and closes modal.

Yii2 Pjax not working

I want to refresh the gridview using Pjax but somehow it is not working. Here is the code:
_search.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\widgets\Pjax;
$this->registerJs("
$('#btnAjaxSearch').click(function(){
$.ajax({
type: 'get',
data: $('.bank-search form').serializeArray(),
success: function (data) {
$.pjax.reload({container:\"#bank\"});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('error');
}
});
return false;
});
", \yii\web\View::POS_END, 'bank-search');
?>
<div class="bank-search">
<?php Pjax::begin(['id' => 'bank-form']); ?>
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'bank_name') ?>
<?= $form->field($model, 'state') ?>
<?= $form->field($model, 'district') ?>
<?= $form->field($model, 'city') ?>
<div class="form-group">
<?= Html::Button('Search', ['class' => 'btn btn-primary','id' => 'btnAjaxSearch']) ?>
</div>
<?php ActiveForm::end(); ?>
<?php Pjax::end(); ?>
</div>
index.php
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
$this->title = 'Banks';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="bank-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Bank', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php Pjax::begin(['id' => 'bank']); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'bank_name',
'state',
'district',
'city',
// 'branch',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
<?php Pjax::end(); ?>
</div>
Controller
/**
* Lists all Bank models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new BankSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
Simple search is working but Pjax is not. I am new to Yii2 so any help would be appreciated. Thank you.
Thanks Edin. It helped me to solved the problem. Here is what I did. It might help someone facing the same problem.
As Edin mentioned you need to pass the url along with the search parameters to the Pjax in order to refresh the gridview.
Here's my edited code :
$js = <<<JS
// get the form id and set the event
$('#bank-form-id').on('beforeSubmit', function(e) {
var form = $(this);
if(form.find('.has-error').length) {
return false;
}
$.ajax({
url: form.attr('action'),
type: 'post',
data: form.serialize(),
success: function(response) {
var csrf = yii.getCsrfToken();
var bank_name = $('#banksearch-bank_name').val();
var state = $('#banksearch-state').val();
var district = $('#banksearch-district').val();
var city = $('#banksearch-city').val();
var url = form.attr('action')+ '&_csrf='+csrf+'&BankSearch[bank_name]='+bank_name+'&BankSearch[state]='+state+'&BankSearch[district]='+district+'&BankSearch[city]='+city;
$.pjax.reload({url: url, container:'#bank'});
}
});
}).on('submit', function(e){
e.preventDefault();
});
JS;
$this->registerJs($js);
The way Pjax is working is by sending another request with special headers. When pjax request is detected only html required to update container is returned from server. Line
$.pjax.reload({container:\"#bank\"});
will send another request, and inside actionIndex queryParams will be empty.
You can solve this by storing search parameters to session or by specifing pjax url with parameters in query string.
Try following:
var url = urlWithFilters();
$.pjax({url: url, container: '#bank'});
In this case you don't need to create own ajax call, just create url with with filters.