Yii2 render view as modal, Pop up Window for forms - yii2

Render view page as a modal for preview:
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::button('Create Branches', ['value'=>Url::to(['/branches/create']),'class' => 'btn btn-success','id'=> 'modalButton']) ?>
</p>
<?php
Modal::begin([
'header'=>'<h4>Branches</h4>',
'id'=>'modal',
'size'=>'modal-lg',
]);
echo "<div id='modalContent'></div>";
Modal::end();
?>
My controller:
public function actionCreate()
{
return $this->renderAjax('create', [
'model' => $model,
]);
}
My script:
$(function () {
$('#modalButton').click(function () {
$('#modal').modal('show')
.find('#modalContent')
.load($(this).attr('value'));
});
});
But when I click the link it open a viewpage with no CSS, not a pop-up modal. Please help me with this. Thank you

You can update your code as this.
<h1><?= Html::encode($this->title) ?></h1>
<p>
<!-- updated id to class here -->
<a class="modalButton btn btn-success" href="<?=Url::to(['/branches/create']) ?>">
</p>
<?php
Modal::begin([
'header'=>'<h4>Branches</h4>',
'id'=>'modal',
'size'=>'modal-lg',
]);
echo "<div id='modalContent'></div>";
Modal::end();
?>
Update Jquery event.
$(function(){
// changed id to class
$('.modalButton').on('click', function (){
$.get($(this).attr('href'), function(data) {
$('#modal').modal('show').find('#modalContent').html(data)
});
return false;
});
});

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 submit modal form with ajax

I've success create modal form, but I can't submit it with ajax. Everytime i click submit button it not stay in the index page but instead show echo 1 from my Controller.
My controller
public function actionCreate()
{
$model = new Testing();
if ($model->load(Yii::$app->request->post())) {
if($model->save()){
echo 1;
}else{
echo 0;
}
}else{
return $this->renderAjax('create', [
'model' => $model,
]);
}
}
My form
<div class="testing-form">
<?php $form = ActiveForm::begin(['id' => $model->formName()]); ?>
<?= $form->field($model, 'test')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php
$this->registerJS("
$('form#{$model->formName()}'.on('beforeSubmit', function(e)
{
var \$form = $(this);
$.post(
\$form.attr('action'),
\$form.serialize()
)
.done(function(result) {
if(result == 1)
{
$(\$form).trigger('reset');
$.pjax.reload({container:'#issuehrGrid'});
}else
{
$('#message').html(result.message);
}
}).fail(function()
{
console.log('server error');
})
return false;
});"
);
?>
My view
<div class="report">
<h3>HR Issues</h3>
<?= Html::a('<span class="glyphicon glyphicon-plus"></span> Add', ['create'], ['class' => 'btn btn-success modalButton']) ?>
<?php Pjax::begin(['id'=>'issuehrGrid']); ?>
<table class="table table-bordered table-hover">
<tbody>
<?php foreach ($dataProvider->models as $hr) {
?>
<tr>
<td><?=$hr->test;?></td>
</tr>
<?php } ?>
</tbody>
</table>
<?php Pjax::end(); ?>
</div>
Please help me with this.
Thank you!
What I suspect is that it would be showing you the blank page with 1 displayed in it is because after the first submission your Pjax grid is reloaded via the statement
$.pjax.reload({container:'#issuehrGrid'});
and once reloaded your beforeSubmit event is not bound again to the form as the form Html is reloaded again and when you submit the form second time it just makes a simple form submit and displays the blank page with 1, you need to use the pjax:complete event for the pjax, so that one the grid is reloaded your script binds the beforeSubmit event to the form again.
Also, you have a syntax error in your script which should be fixed. Change your script to the following
<?php
$formName = $model->formName();
$js = <<<JS
$(document).on("ready pjax:complete",function(){
$('form#{$formName}').on('beforeSubmit', function(e){
var \$form = $(this);
$.post(
\$form.attr('action'),
\$form.serialize()
).done(function(result) {
if(result == 1)
{
$(\$form).trigger('reset');
$.pjax.reload({container:'#issuehrGrid'});
}else
{
$('#message').html(result.message);
}
}).fail(function()
{
console.log('server error');
})
return false;
});
});
JS;
$this->registerJS(
$js,
\yii\web\View::POS_READY
);
?>
UPDATE
and dont forget to change the controller action code and change the echo 1 to return 1 and echo 0 to return 0

Yii2 render view as modal

I want to render view page as a modal for preview
<div>
<?php foreach($softs as $soft) { ?>
<a id="modalButton" href="<?=Url::to(['documents/view', 'id'=>$soft->id]); ?>"><h3><?=$soft->title; ?></h3></a>
<?php
Modal::begin([
'header' => 'Test',
'id' => 'modal',
'size' => 'modal-lg',
]);
echo "<div id='modalContent'></div>";
Modal::end();
?>
<?php } ?>
</div>
My controller
public function actionIndex()
{
$query = Documents::find();
$softs = $query->where(['type_id' => 2])->all();
return $this->render('index', [
'softs' => $softs,
]);
}
public function actionView($id)
{
return $this->renderAjax('view', [
'model' => $this->findModel($id),
]);
}
My script
$(function(){
$('#modalButton').click(function (){
$('#modal').modal('show')
.find('#modalContent')
.load($(this).attr('href'));
});
});
But when I click the link it open a viewpage with no CSS, not a pop-up modal.
Please help me with this. Thank you
You update your code as per below.
<div>
<?php foreach($softs as $soft) { ?>
<!-- updated id to class here -->
<a class="modalButton" href="<?=Url::to(['documents/view', 'id'=>$soft->id]); ?>"><h3><?=$soft->title; ?></h3></a>
<?php } ?>
<!-- We don't need to print modal popup multiple times -->
<?php
Modal::begin([
'header' => 'Test',
'id' => 'modal',
'size' => 'modal-lg',
]);
echo "<div id='modalContent'></div>";
Modal::end();
?>
</div>
Update click event.
$(function(){
// changed id to class
$('.modalButton').click(function (){
$.get($(this).attr('href'), function(data) {
$('#modal').modal('show').find('#modalContent').html(data)
});
return false;
});
});

Yii2 modal height issue

I've been using bootstrap modal on some form. I have learned from this tutorial to create modal. For my previous project I didn't have any issue with the modal. But for my current project the modal body is not fully covering the modal content. Here's the screenshot
I solved this problem for now by referring this. I'm not able to figure out what could be causing the height issue.
My view file code
<div class="collection-type-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::button('Create Collection', ['value' => Url::to('index.php?r=settings/collectiontype/create'), 'class' => 'btn btn-success', 'id' => 'modalButton']) ?>
</p>
<?php // Modal for create
Modal::begin([
'header'=>'Collection Type',
'id'=>'modal',
'size'=>'modal-lg',
]);
echo "<div id='modalContent'></div>";
Modal::end();
?> <!-- end modal -->
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'type',
'days',
'created_by',
'modified_by',
// 'status',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
My controller create action code
public function actionCreate() {
$model = new CollectionType();
$model->created_by = Yii::$app->user->identity->username;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
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]);
}
}
}
And my js code
$(function(){
$('#modalButton').click(function(){
$('#modal').modal('show')
.find('#modalContent')
.load($(this).attr('value'));
});
$('#modal').on('show.bs.modal', function () {
$('.modal-lg .modal-content').css('height',$( window ).height()*0.55);
});
});
As I said I've solved the problem by using the above js script but I don't think this is the best solution as I would have to set the height manually like this for every modal. What could be causing this problem? Has anyone faced this issue and solve?
This looks like a problem with floats. Modify the view generated inside the modal:
Wrap the content of this modal between <div class="clearfix"> and </div>.
OR
Add <div class="clearfix"></div> at the end of this view.

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']
];
...
}
?>