Yii2 Pjax on ActiveForm and GridView [ Got it Working] - yii2

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.

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>

Catch button in controller

I have this form in view
<?php
$form = ActiveForm::begin();
$items = [201 => 'Тест', 202 => 'Тест2'];
echo Html::dropDownList('list', 'null', $items);
?>
<div class="form-group">
<?=
Html::submitButton(
'Удалить отмеченные',[
'data' => ['confirm' => 'Вы действительно хотите перенести отмеченные товары в выбранную категорию?'],
'name' => 'deleteProduct',
'value' => 'delProduct', // добавить value
'class' => 'btn btn-danger'
])
?>
</div>
<?php ActiveForm::end(); ?>
And this in controller
if (Yii::$app->request->post('deleteProduct'))
{
$lk_number = $_POST['list'];
print_r($lk_number);exit();
}
But when click on button there is no catch in controller. What I do wrong?

Insert multiple records of a same table Yii2

I want to insert same record in one table. I have only one input array in the below form but i want to save multiple time record for label input array.
my form is
<div class="surveys-questions-form">
<?php $form = ActiveForm::begin(); ?>
<?php
if(isset($_GET['option_id']) and $_GET['option_id'] > 0)
$id= $_GET['option_id'];
else
$id= $model->option_id;
echo $form->field($model, 'question_id')->hiddenInput(['value' => $id])->label(false);
?>
<div class="col-md-6">
<div id="question_wrapper">
<?= $form->field($model, 'type')->dropDownList([ 'text' => 'Text', 'numbers' => 'Numbers', 'date' => 'Date', 'texarea' => 'Texarea', 'checkbox' => 'Checkbox', 'radio' => 'Radio', 'rating' => 'Rating', ], ['prompt' => '']) ?>
<div id="add_more_field">
<?= $form->field($model, 'label[]')->textInput(['maxlength' => true]) ?>
</div>
<div class="form-group">
<?php
echo Html::a('Add more', 'javascript:void(0);', [
'id' => 'surveys-questions-new-button',
'class' => 'pull-right btn btn-primary btn-xs'
])
?>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
</div>
<?php ActiveForm::end(); ?>
</div>
and controller
public function actionCreate()
{
$model = new QuestionsOptions();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->option_id]);
} else {
return $this->renderAjax('create', [
'model' => $model,
]);
}
}
Give me the following error when i try to submit form.
Label must be a string.
My $_POST array
Array
(
[_csrf-backend] => LXBhajI3YVpOIikeRWYHYkNCAD4Kb1ZrQzwER21GL2MdCTgkWm5ZDQ==
[QuestionsOptions] => Array
(
[question_id] => 47
[type] => numbers
[label] => Array
(
[0] => Label1
[1] => Label2
[2] => Labe3
)
)
)
If you want to save multiple record use loop i suggest you to use foreach loop it is best
public function actionCreate()
{
$model = new QuestionsOptions();
if ($model->load(Yii::$app->request->post())) {
if(sizeof(array_filter($_POST['QuestionsOptions']['label'])) > 0){
foreach($_POST['QuestionsOptions']['label'] as $key => $row){
$model->setIsNewRecord(true);
$model->id = null;
$model->label = $row;
$model->save();
}
}
return $this->redirect(['view', 'id' => $model->option_id]);
} else {
return $this->renderAjax('create', [
'model' => $model,
]);
}
}

Yii2 upload image from modal issue

I'm using yii2 bootstrap modal for uploading images, the issue is I need to double click on Create button then form submit works otherwise it don't work on single click.
On double click image is uploading and form data also saved to database.
Is this issue with my code?
Here is code:
//Form
<?php Pjax::begin(['id' => 'banner-form']) ?>
<?php $form = ActiveForm::begin([
'id' => 'banner-form',
'options' => [
'data-pjax' => true,
'enctype' => 'multipart/form-data'
]
]);
?>
<?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'banner')
->fileInput([
"accept"=>"image/*"
])
?>
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
<?php Pjax::end(); ?>
//Model
[['banner'], 'file', 'skipOnEmpty' => false,
'extensions' => ['jpg', 'jpeg', 'png', 'gif']
]
//index.php
<p>
<?= Html::a(Yii::t('app', 'Create Banner'), null, ['class' => 'btn btn-success', 'id'=>'createBannerButton',
'value'=>Url::to(['/banner/create'])]) ?>
</p>
<?php Pjax::begin(['id' => 'banner-index']) ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
....
]); ?>
<?php Pjax::end(); ?>
//Controller
use yii\web\UploadedFile;
class BannerController extends Controller
{
...
public function actionCreate()
{
$model = new Banner();
if ($model->load(Yii::$app->request->post())){
$file = UploadedFile::getInstance($model, 'banner');
if (!empty($file))
$model->banner = $file;
if($model->save()){
if (!empty($file))
$file->saveAs( Yii::getAlias('#root') .'/uploads/' . $file);
return $this->redirect(['view', 'id' => $model->id]);
}
}
else if (Yii::$app->request->isAjax) {
return $this->renderAjax('create', [
'model' => $model,
]);
}
else {
return $this->render('create', [
'model' => $model,
]);
}
}
...
}
//layouts/main.php
<?php
Modal::begin([
'header' => '',
'id' => 'modal',
'size' => 'modal-medium', //medium
'clientOptions' => ['backdrop' => 'static', 'keyboard' => false]
]);
echo "<div id='modalContentBackend'>
<div class='col-lg'>
<img src='/images/loading.gif' width='280' height='210' alt='loading...'>
</div>
</di>";
Modal::end();
?>
<?php $this->endBody() ?>
//backend/web/js/custom.js
$(function(){
$("#createBannerButton").click(function(){
$("#modal").modal('show')
.find('#modalContentBackend')
.load($(this).attr('value'));
});
});
//backend/assets/AppAsset
class AppAsset extends AssetBundle
{
public $basePath = '#webroot';
public $baseUrl = '#web';
public $css = [
'css/site.css',
];
public $js = [
'js/custom.js'
];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
];
}
I got the issue, I'm including Pjax::begin() in index.php and _form.php, I have removed Pjax::begin() from _form.php and now it is working fine.

Yii2 Gridview data not changing in Pjax

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.