How to reload pjax div in modal window in yii2 - yii2

I have used modal for viewing comments list, with modal having an update button and a textbox.
When a user enters some text in the text box and click update button i want the comments list div to be reloaded without the whole page being reloaded or the modal being closed or hided.
I have already read
How to update widget with pjax in modal window in yii2
que. but still not getting solution.
My code is
Registered Js and view file
$this->registerJs("
$(function() {
$('#replayMeg').on('beforeSubmit', function(event, jqXHR, settings) {
var comment = $('#".Html::getInputId($modelReply, 'hdr_comments')."').val();
var ticketId = $model->hdt_id;
$.ajax({
url: '".Url::to(['helpdesk-replies/create'])."',
type: 'post',
data: { replyMsg : comment, ticketId : ticketId},
beforeSend: function() {
if($('#".Html::getInputId($modelReply, 'hdr_comments')."').val() == '')
{
$('.field-helpdeskreplies-hdr_comments').addClass('form-group field-helpdeskreplies-hdr_comments required has-error');
$('.help-block').html('Reply cannot be blank.');
return false;
}
},
success: function(data) {
//$.pjax.reload({container:'#update_replyBox'});
}
});
return false;
})
});
");
<?php yii\widgets\Pjax::begin(['id' => 'update_replyBox']); ?>
<div class="modal-body">
<div class="box-tools pull-right">
<?= $actionBtn; ?>
</div>
</div>
<div class="panel panel-info">
<div class="panel-heading colorchangeheader left-align">
<i class="fa fa-users fa-fw"></i> <?= $model->getUserName($cData['hdr_replay_user_id']); ?> <span class="mobilebreakpoint"><i class="fa fa-clock-o fa-fw"></i><?= Yii::$app->formatter->asDate($cData['created_at']); ?> # <?= Yii::$app->formatter->asTime($cData['created_at']); ?></span>
</div>
<div id="rp8" class="panel-body">
<?= $cData['hdr_comments'] ?>
</div>
</div>
<?php $form = ActiveForm::begin(['id' => 'replayMeg']); ?>
<div class="box-body">
<div class='row'>
<div class='col-sm-12'>
<?=
$form->field($modelReply, 'hdr_comments')->widget(RemainingCharacters::className(), [
'type' => RemainingCharacters::INPUT_TEXTAREA,
'name' => 'message_body',
'id' => 'message_body-textarea',
'text' => Yii::t('app', '{n} Characters Remaining'),
'label' => [
'tag' => 'p',
'id' => 'my-counter',
'class' => 'counter text-aqua',
'invalidClass' => 'error'
],
'options' => [
'rows' => '3',
'class' => 'form-control replyTextArea',
'maxlength' => 200,
'placeholder' => Yii::t('app', 'Write something'),
]
]);
?>
</div>
</div>
<!--/div>
<div class="box-footer"-->
<?= Html::button('<i class="fa fa-reply"></i> '.Yii::t('comm', 'Reply'), ['class' => 'btn btn-info btn-create submit', 'type' => 'submit']) ?>
</div>
<?php ActiveForm::end(); ?>
<?php yii\widgets\Pjax::end() ?>

Please try to set backdrop false in the modal
'clientOptions' => ['backdrop' => false]
or
Set data-pjax true in your active form
<?php $form = ActiveForm::begin(['options' => ['data-pjax' => true ]]); ?>
For more details http://www.yiiframework.com/wiki/772/pjax-on-activeform-and-gridview-yii2/
For more options on Modal Refer

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 Pjax reloads the page even with renderPartial

I am sending Pjax request which reloads the whole page even when I am using renderPartial. The pjax container is #promo-products than why it reloads the whole page not only fill the container with the desired results ? If I var_dump($child_products);die; it shows the result right in the container but without die it reloads the page. Also tried to render a partial view ( like _children lets say ) but the result was the same. What is my mistake?
Controller:
public function actionCreate()
{
$model = new Promotion();
$products = [];
$success = null;
$child_products = [];
if(Yii::$app->request->isPjax){
$parent_id = Yii::$app->request->get('parent_id');
if($parent_id){
$parent_children = ProductChild::find()->where(['id_in' => $parent_id])->all();
foreach ($parent_children as $child){
$child_products[$child['id']][] = $child;
}
}
}
if (!Yii::$app->request->isPjax && $model->load(Yii::$app->request->post())) {
$transaction = Yii::$app->db->beginTransaction();
try{
if($model->save()){
//save products
$model->saveProducts();
$transaction->commit();
return $this->redirect(['index', 'success' => 1]);
} else {
throw new \Exception("Some error occurred.");
}
}catch (\Exception $e){
$success = 3;
$model = new Promotion();
$transaction->rollBack();
}
}
if(Yii::$app->request->isPjax){
return $this->renderPartial('create', [
'child_products' => $child_products,
]);
}
return $this->render('create', [
'model' => $model,
'products' => $products,
'success' => $success,
'child_products' => $child_products,
]);
}
And my view:
<?php
use yii\widgets\ActiveForm;
use backend\helpers\Header;
use kartik\select2\Select2;
use yii\web\JsExpression;
use backend\helpers\CGrowl;
\backend\assets\JquerySteps::register($this);
\backend\assets\DateTimePickerAsset::register($this);
/* #var $this yii\web\View */
/* #var $model backend\models\Contact */
/* #var $form yii\widgets\ActiveForm */
$this->registerJs("
$('#promotion-start_date').bootstrapMaterialDatePicker({ format: 'YYYY-MM-DD HH:mm:ss' });
$('#promotion-end_date').bootstrapMaterialDatePicker({ format: 'YYYY-MM-DD HH:mm:ss' });
",
\yii\web\View::POS_LOAD,
'datetime-picker-init'
);
if (isset($success)) {
echo CGrowl::setFormResult((int)$success, $this);
}
?>
<div class="row page-titles" style="background-image: url('<?= Yii::getAlias('#backend-image') ?>/theme/images/heading-title-bg.jpg')">
<div class="col-md-12">
<h4 class="text-white"><?= Yii::t('app', 'Promotion') ?></h4>
</div>
<div class="col-md-6">
<?= Header::renderBreadcrumbs($this) ?>
</div>
</div>
<div class="row" id="validation">
<div class="col-12">
<div class="card wizard-content">
<div class="card-body">
<div class="panel-body">
<?php $form = ActiveForm::begin([
'options' => [
'class' => 'validation-wizard wizard-circle'
],
]); ?>
<h6><?= Yii::t('app', 'Main info') ?></h6>
<section>
<div class="row">
<div class="col-sm-6">
<?= $form->field($model, 'type')->widget(Select2::class, [
'data' => [
1 => Yii::t('app', 'Percentage'),
2 => Yii::t('app', 'Price'),
],
'options' => [
'placeholder' => Yii::t('app', 'Type')
],
'pluginOptions' => [
'allowClear' => true
]
]) ?>
</div>
<div class="col-sm-6">
<?= $form->field($model, 'value')->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-6">
<?= $form->field($model, 'start_date')->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-6">
<?= $form->field($model, 'end_date')->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-4">
<?= $form->field($model, 'products')->widget(Select2::class, [
'initValueText' => $products,
'options' => [
'multiple' => true
],
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 3,
'language' => [
'errorLoading' => new JsExpression("function(){return 'Waiting for results ...'; }"),
],
'ajax' => [
'url' => \yii\helpers\Url::to(['async/products']),
'dataType' => 'json',
'data' => new JsExpression("function(params){return {q:params.term}; }")
],
'escapeMarkup' => new JsExpression("function(markup){return markup;}"),
'templateResult' => new JsExpression("function(city){return city.text;}"),
'templateSelection' => new JsExpression("function(city){return city.text;}")
],
'pluginEvents' => [
'select2:select' => "function(){
let url = location.href.split('?')[0]
$.pjax.defaults.timeout = false
$.pjax({
url: url,
data: {
parent_id: this.value
},
container: '#promo-products'
})
}"
]
]) ?>
</div>
<div class="col-sm-8">
<label for=""><?= Yii::t('app', 'Varieties')?></label>
<div class="table-responsive">
<table>
<?php \yii\widgets\Pjax::begin(['id' => 'promo-products']) ?>
<tbody>
<?php
foreach ($child_products as $child){
echo $child->id;
}
?>
</tbody>
<?php \yii\widgets\Pjax::end() ?>
</table>
</div>
</div>
<div class="col-sm-12">
</div>
</div>
</section>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
</div>
</div>

Yii2 - Dynamic Form with a single model

I have always worked with Dynamic Form that saved in multiple models, especially wbraganca. However, I want to create a Dynamic Form whereby everything will be saved on the same Model Class, CentreProgramme. When the Add button is clicked, Dropdownlist with attribute Programme_id will be created.
How do I achieve this.
I used the code shown below, but the Dropdown is not wide enough to accommodate on the data. When I select all from the dropdown, it spreads accross the dropdown because the data is too large. Thanks
I have this Model Class
CentreProgramme
public function attributeLabels()
{
return [
'id' => Yii::t('centre', 'ID'),
'state_office_id' => Yii::t('centre', 'State Office'),
'study_centre_id' => Yii::t('centre', 'Study Centre'),
'programme_id' => Yii::t('centre', 'Programme'),
];
}
Controller
public function actionCreate()
{
$model = new StudyCentreProgramme();
if ($model->load(Yii::$app->request->post()) && isset($_POST['StudyCentreProgramme'])) {
$model->attributes = $_POST['StudyCentreProgramme'];
for($i=0;$i<count($_REQUEST['StudyCentreProgramme']['programme_id']);$i++) :
$model->id = NULL;
$model->isNewRecord = true;
$model->programme_id = $_POST['StudyCentreProgramme']['programme_id'][$i];
$model->state_office_id = $_POST['StudyCentreProgramme']['state_office_id'];
$model->study_centre_id = $_POST['StudyCentreProgramme']['study_centre_id'];
if($model->save()) {
Yii::$app->session->setFlash('green-'.$i, '<i class="fa fa-info-circle"></i> <b>Study Centre Programme: </b> is created successfully');
} else {
Yii::$app->session->setFlash('red-'.$i, '<i class="fa fa-warning"></i><b>Study Centre Programme: </b> has already been taken.');
}
endfor;
return $this->redirect(['index']);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
View
<?php $form = ActiveForm::begin([
'id' => 'study-centre-programme-form',
'fieldConfig' => [
'template' => "{label}{input}{error}",
],
]); ?>
<div class="col-xs-12 col-sm-6 col-lg-6">
<?= $form->field($model, 'state_office_id')->dropDownList(ArrayHelper::map(\common\models\StateOffice::find()->where(['is_status' => 0])->all(),'id','state_name'),
[
'prompt'=>Yii::t('app', '--- Select State Officee ---'),
'onchange'=>'
$.get( "'.Url::toRoute('dependent/getprogrammestudycentre').'", { id: $(this).val() } )
.done(function( data ) {
$( "#'.Html::getInputId($model, 'state_office_id').'" ).html( data );
}
);'
]
); ?>
</div>
<div class="col-xs-12 col-sm-6 col-lg-6">
<?= $form->field($model, 'state_office_id')->dropDownList([''=>Yii::t('app', '--- Select Study Centre ---')]); ?>
</div>
<div class="col-xs-12 col-sm-12 col-lg-12">
<?php
if(Yii::$app->controller->action->id === 'create' ) {
echo $form->field($model, 'programme_id[]')->dropDownList(ArrayHelper::map(common\models\Programme::find()->where(['is_status' => 0])->all(),'id','programme_name'),['multiple' => "multiple", 'class'=>'form-control', 'placeholder' => $model->getAttributeLabel('programme_id')]);
} else {
echo $form->field($model, 'programme_id')->dropDownList(ArrayHelper::map(common\models\Programme::find()->where(['is_status' => 0])->all(),'id','programme_name'),['class'=>'form-control', 'placeholder' => $model->getAttributeLabel('programme_id')]);
}
?>
</div>
<div class="form-group col-xs-12 col-sm-6 col-lg-4 no-padding jkkesrmsArLangCss">
<div class="col-xs-6">
<?= Html::submitButton($model->isNewRecord ? Yii::t('centre', 'Create') : Yii::t('centre', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-block btn-success' : 'btn btn-block btn-info']) ?>
</div>
<div class="col-xs-6">
<?= Html::a(Yii::t('centre', 'Cancel'), ['index'], ['class' => 'btn btn-default btn-block']); ?>
</div>
</div>
<?php ActiveForm::end(); ?>
[

yii2 modal loading content but header modal can not see it

I can not understand why I do not show well the modal can you help?
Modal
<?php
Modal::begin([
'header' => '<h2>Accedi</h2>',
'id' => 'modalSmall',
'size' => 'modal-sm',
//keeps from closing modal with esc key or by clicking out of the modal.
// user must click cancel or X to close
'clientOptions' => ['backdrop' => 'static', 'keyboard' => true],
'footer' => 'fdd'
]);
echo "<div id='modalContent'></div>";
Modal::end();
?>
JS
$(function() {
$('#modalButton a').click(function(e) {
e.preventDefault();
$('#modalSmall').modal('show')
.find('.modal-content')
.load($(this).attr('href'));
});
});
what I see
there is not the close button
<?php
Modal::begin([
'header' => '',
'headerOptions' => ['id' => 'modalHeader'],
'id' => 'modalSmall',
'size' => 'modal-medium', //medium
'clientOptions' => ['backdrop' => 'static', 'keyboard' => false]
]);
echo "<div id='modalContent'>
<div class='col-lg'>
<img src='".Yii::$app->request->baseUrl."/loading.gif' width='280' height='210' alt='loading...'> // put loading.gif in backend/web/ directory
</div>
</di>";
Modal::end();
?>
$(function() {
$('#modalButton').click(function(e) {
e.preventDefault();
$('#modalSmall').modal('show')
.find('.modal-content')
.load($(this).attr('value'));
document.getElementById('modalHeader').innerHTML = '<button aria-hidden="true" data-dismiss="modal" class="close" type="button">×</button><h3>' + $(this).attr('title') + '</h3>';
});
});
How to call?
use yii\helpers\Url;
<p>
<?= Html::a(Yii::t('app', 'Add Something'), null, ['class' => 'btn btn-success', 'id'=>'modalButton',
'value'=>Url::to(['/controller/action']),
'title'=>'Show in Modal header'
])
?>
</p>

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.