Yii2 render view as modal - yii2

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;
});
});

Related

Yii2 render view as modal, Pop up Window for forms

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;
});
});

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

select2 and Pjax not work together in yii2

when i use pjax in yii2. selec2 widget stops working. while select2 working alone. (not working together)
im using select2 widgets and pjax together. but when submit form with pjax. in new form, select2 not work. (just show loading img). pls help me
what is problem?
I want to use both at the same time.
select2 extention page
in view:
<?php
use yii\helpers\Hrml;
use yii\widgets\Pjax;
/* #var $this yii\web\View */
/* #var $model app\models\Vitrin */
?>
<?php Pjax::begin(); ?>
<?php
if($model->getProductTypeSetting()=='both')
{
echo $this->render('_form', [
'model' => $model,
]);
}
?>
<?php Pjax::end(); ?>
in _form:
<!-- BEGIN PAGE CONTENT-->
<?= Html::beginForm(['vitrin/index', 'id' => $id], 'post'['data-pjax' => '']); ?>
<?= Html::activeInput('text', $model, 'name', ['class' => $username]) ?>
<?= Html::submitButton('Submit', ['class' => 'submit']) ?>
<?= Html::endForm() ?>
<!-- END PAGE CONTENT-->
in controller:
if(Yii::$app->request->post('productType'))
{
$model->productType = $_POST['productType'];
if($model->productType=='physical')
{
return $this->renderAjax('_formProduct', ['products' => $this->getProductName()]);
}
else
throw new \yii\web\HttpException(406, Yii::t('app', 'Your request is invalid.'));
}
in _formProduct:
<!-- BEGIN PAGE CONTENT-->
<?= Html::beginForm(['vitrin/index', 'id' => $id], 'post', ['data-pjax' => '']); ?>
<?php
echo Select2::widget([
'name' => 'name',
'data' => [1 => "First", 2 => "Second", 3 => "Third", 4 => "Fourth", 5 => "Fifth"],
'options' => [
'placeholder' => 'Select a type ...',
],
]);
?>
<?= Html::submitButton('Submit', ['class' => 'submit']) ?>
<?= Html::endForm() ?>
<!-- END PAGE CONTENT-->
and AppAssets class:
class AppAsset extends AssetBundle
{
public $basePath = '#webroot/themes/backend';
public $baseUrl = '#web/themes/backend/assets_t';
public $css = [
'bootstrap-rtl/css/bootstrap-rtl.min.css',
'bootstrap-rtl/css/bootstrap-responsive-rtl.min.css',
'font-awesome/css/font-awesome.css',
'fancybox/source/jquery.fancybox.css',
'uniform/css/uniform.default.css',
];
public $js = [
'bootstrap-rtl/js/bootstrap.min.js',
'js/jquery.blockui.js',
'uniform/jquery.uniform.min.js',
];
when submit _form with pjax. in _formProduct, select2 not work. (just show loading img).
Generally, when I use Pjax, other Js codes are deactivated.
In your view header:
use kartik\select2\Select2Asset;
Select2Asset::register($this);
Also make sure you have the latest Select2 widget.