yii2 customize a bootbox modal instead of alert on data-confirm - javascript

For example here I want to change alert for a bootbox.alert(...
'delete' => function ($url, $model, $key) {
return Html::a('<span class="glyphicon glyphicon-trash"></span>', $url, [
'title' => Yii::t('yii', 'Delete'),
'class'=>'btn btn-primary',
'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'),
'data-method' => 'post',
'data-pjax' => '0',
]);
},

Just add a HTML class to the element, drop the "data-confirm" param and use a "click" event.
That way you can execute whatever you want when the link is clicked.
'delete' => function ($url, $model, $key) {
return Html::a('<span class="glyphicon glyphicon-trash"></span>', $url, [
'title' => Yii::t('yii', 'Delete'),
'class'=>'btn btn-primary delete-button',
'data-id' => $model->id, // For using when the button is clicked
]);
},
And inside your javascript file:
$(".delete-button").on("click",function(e){
e.preventDefault();
var modelId = $(this).data('id');
// Run bootbox.alert() here!!
// Based on the bootbox result, you can decide to fire the initial event again:
// $(this).unbind('submit').submit()
});
Hope it helps :)

Just assign a class name or id : "id"=>"btn-id"
Then override click event :
$("#btn-id").on("click",function(e){
e.preventDefault();
//Somethings and return here
}));

Link Overriding yii.js confirm --> bootbox.confirm.
Yii 2.0: Escape from Default's Yii2 Delete Confirm Box :

Related

Set a twig value with JS

I've seen many topics about questions like mine, but I can't get any solutions.
I'm using Symfony, and I have a twig template which displays a form.
Imagine that I have this line :
{{ form_row(demandeForm.distinction) }}
Thanks to this :
->add('distinction',null, [
'label_attr' => array('id' => "distinct_form"),
'required' => false,
'label' => 'distinction'
])
I also have a submit button. My wish is to modify the value of my row "distinction" when the button is clicked (id of the submit button : formDepot).
Here is my code :
$(document).ready(function(){
$('#formDepot').click(function(){
$('#distinct_form').value('555');
});
});
When I retrieve my datas on submit, I don't have any value in my "distinction".
Any ideas ?
Thanks
This is because you're applying the changes on the label value, not on the input itself.
'label_attr' => array('id' => "distinct_form") and in js : $('#distinct_form').val('555');
Change the form builder to this :
->add('distinction',
null,
[
'attr' => array('id' => "distinct_form"),
'required' => false,
'label' => 'distinction'
])
With attr for the field (not the label), you can try
$('#distinct_form').val('555'); not .value();
You are assigning a value, instead of getting the value, try this .....
$(document).ready(function(){
$('#formDepot').click(function(){
$('#distinct_form').val();
});

yii2 - How to set kartik select2 value in javascript

I try to set value to kartik select2 in javascript action but still no luck.
here is my code in view files:
<div class="col-xs-6">
<?= $form->field($model, 'item_id')->widget(kartik\select2\Select2::className(), [
'data' => \yii\helpers\ArrayHelper::map(\app\models\ItemProduction::find()->all(), 'id', 'name'),
'options' => ['placeholder' => 'Select item'],
'pluginOptions' => [
'allowClear' => true,
],
]) ?>
</div>
and my javascript code like this
$(document).on('click', '.select-row', function(){
// get id from custom button
var id = $(this).attr('data-id');
$.get('../ticket-timbangan/get-ticket', {id : id}, function(data){
var data = $.parseJSON(data);
alert(data.item_id);
$('#pengirimanproduksi-ticket_id').val(data.id);
$('#select2-pengirimanproduksi-item_id-container').val(data.item_id).trigger('change');
$('#pengirimanproduksi-bruto_tbg').val(data.bruto);
$('#pengirimanproduksi-tara_tbg').val(data.tara);
$('#pengirimanproduksi-remark').val(data.remark);
});
$('#modalTicketList').modal('hide');
});
this is I inspect kartik select2 element
<span class="select2-selection__rendered" id="select2-pengirimanproduksi-item_id-container"><span class="select2-selection__placeholder">Select item</span></span>
I try this code $('#select2-pengirimanproduksi-item_id-container').val(data.item_id).trigger('change'); but it changes nothing.
Please advice. thanks.
first id for select2 is wrong.
$('#select2-pengirimanproduksi-item_id-container')
don't confuse with this and use regular one according to your view name, like mine is $('#pengirimanproduksi-item_id').val(your_value).trigger('change') should work.
just reading select2 documentation.
you can give your own id:
'options' => ['placeholder' => 'Select item','id' => 'your_id'],

Retrieve data from modal without refreshing

I have an h4 tag and a button. The button opens a modal with a GridView whose action column contains a button in order to select the row.
What I need the row button to do is closing the modal and populate the h4 tag with "Row 3 was selected", for instance. But I don't want the page to be reladed.
This is the parent page tag and button:
<h4>*</h4>
<?
echo Html::button('Explotación', [
'value' => Url::to('/explotaciones/seleccionar'),
'class' => 'btn btn-primary',
'id' => 'modalButton'
]);
Modal::begin([
'header' => 'Seleccionar Explotación',
'id' => 'modal',
'size' => 'modal-md'
]);
echo "<div id= 'modalContent'></div>";
Modal::end();
?>
The action column in the modal:
[
'class' => 'yii\grid\ActionColumn',
'template' => '{seleccionado}',
'buttons' => [
'seleccionado' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-chevron-right"></span>', '#', [
'id' => 'seleccionado_' . $model->exp_id,
'class' => 'seleccionado',
'data-fila' => $model->exp_id
]);
}
]
]
Registering the javascript in the modal:
<?
$assets_js = Yii::$app->assetManager->publish(__DIR__ . '/js');
$this->registerJsFile($assets_js[1] . '/seleccion.js', [
'depends' => [
'app\assets\AppAsset'
]
]);
?>
And the javascript itself:
(function($){
$(document).ready(function() {
$('.seleccionado').click(function(evento) {
var value = 'HELLO';
alert(value);
value = $(this).data("fila");
alert(value);
$('h4').html(value);
$('#modal').modal('hide');
});
});
})(jQuery);
The code prints the HELLO alert but it does not print the second one nor poupulates the h4 tag nor closes the modal.
Which is the right way to make this work?
Erasing the cache in order to reload javascript changes correctly did the trick. Thanks anyway.

Yii2: Get values to update form in modal window

I am using Yii2 modal to update a form in modal window but I am unable to fetch the values to be already filled in the form.
In this screen-shot link below:
http://awesomescreenshot.com/0f957qq367
When I click on edit option, It takes me to the update form which is opened in a modal window. But this form shows empty values in all fields. I want to update the form.
Please find this in this screen-shot below:
http://awesomescreenshot.com/0f257qqscb
This is the snippet for what I have tried yet:
<?php
use yii\bootstrap\Nav;
use yii\bootstrap\Modal;
Modal::begin([
'id'=>'modalEdit',
//'header' => '<h2>Hello world</h2>',
'size'=> 'modal-lg',
//'toggleButton' => ['label' => 'click me'],
]);
$newmodel = new Backlog();
// $newmodel->id;
echo $this->render('/backlog/update', ['model' => $newmodel]);
Modal::end();
echo Nav::widget([
'options' => ['class' => 'nav-pills navbar-right'],
'encodeLabels' => false,
'items' => [
['label' => '', 'items' => [
['label' => '<span data-toggle="modal" data-target="#modalEdit" style="cursor: pointer;">Edit</span>','url' => 'javascript:void(0);'],
'<li class="divider"></li>',
['label' => '<span>Assign</span>', 'url' => ['#']],
'<li class="divider"></li>',
['label' => '<span>Convert To Backlog</span>', 'url' => ['#']],
'<li class="divider"></li>',
['label' => '<span>Close</span>', 'url' => ['#']],
]],
],
]);
if Backlog is an ActiveRecord Replace the Line with this.
$newmodel = Backlog::findOne(['ID'=>$id]);
Finally, I solved the problem using javascript and ajax loading :
$(document).on("click",".edit-backlog",function(e){
var back_l_id=$(this).attr("b-id");
var modal_body=$("#modalEdit").find(".modal-body");
$.ajax({
url:getAjaxUrl('backlog','update'),
data:{'id':back_l_id},
success:function(res){
//console.log(res);
modal_body.html(res);
}
});
});
I added a class .edit-backlog to span and get the id ("b-id") and used in the above script. Hope this answer helps others too.

Yii: Javascript & CSS not loading after Ajax calls

I have created a view with tabs and each tab has a form with ajax submit and gridview. I am using renderpartial in tabs widget to render the form and gridview and after clicking submit it filters the gridview. Everything looks fine within the tab till I click the submit button. After clicking submit it filters the gridview as expected.. but it does not load the bootstrap javascript and css so the layout is totally messed up and the tabs and menu bar all appears as a list and the page keeps on loading.
Anyone know why is it not loading the required scripts and css which I have preload in main config. Do I have to specify something seperately when calling ajax function from a view.
EDIT: Code Added
Code for tabs widget(producers.php)
<?php $this->widget(
'bootstrap.widgets.TbTabs',
array(
'type' => 'tabs',
'tabs' => array(
array('label' => 'Monthly' ,'id' => 'tab1',
'content' => $this->renderPartial('_prod_monthly',array('dataProvider' => $dataProvider,'dataProvider2' => $dataProvider2 ,'dataProvider3' => $dataProvider3, 'opm' => $opm, 'month' => $month),true,true),
'active' => true),
array('label' => 'Weekly' ,'id' => 'tab2',
'content' => $this->renderPartial('_prod_weekly',array('dataProvider4' => $dataProvider4,'dataProvider5' => $dataProvider5 ,'dataProvider3' => $dataProvider3, 'opm' => $opm, 'week' => $week),true,true)),
array('label' => 'Daily', 'id' => 'tab3', 'content' => 'ABC' )),
)); ?>
Code for partial view (_prod_monthly.php):
$form = $this->beginWidget(
'bootstrap.widgets.TbActiveForm',array(
'id' => 'form_monthly',
'enableAjaxValidation'=>true,
'type' => 'inline',
'method' => 'get',
'htmlOptions' => array('class' => 'well','onsubmit'=>"return false;",/* Disable normal form submit */
'onkeypress'=>" if(event.keyCode == 13){ send2(); } " /* Do ajax call when user presses enter key */),)); ?>
Select Month:
<?php echo CHtml::dropDownList('month', $month,
$sel_month); ?>
Select Employee:
<?php echo CHtml::dropDownList('opm', $opm,
$sel_opm); ?>
<?php $this->widget('bootstrap.widgets.TbButton',
array(
'buttonType'=>'button',
'label'=>'Submit',
'type' =>'primary',
'htmlOptions'=> array('onclick' => 'send2()'),)
);
$this->endWidget();
$this->widget('bootstrap.widgets.TbExtendedGridView', array(
'sortableRows'=>true,
'afterSortableUpdate' => 'js:function(id, position){ console.log("id: "+id+", position:"+position);}',
'type'=>'striped bordered hover',
'dataProvider'=>$dataProvider,
'type'=>'striped bordered responsive',
'template' => "{summary}\n{items}\n{extendedSummary}\n{exportButtons}"));?>
<script type="text/javascript">
function send2()
{
var data=$("#form_monthly").serialize();
$.ajax({
type: 'GET',
url: '<?php echo Yii::app()->createAbsoluteUrl("op/producers"); ?>',
data:data,
success:function(data){
document.write(data);
},
error: function(data) { // if error occured
alert("Error occured.please try again");
alert(data);
},
dataType:'html'});
}
</script>
Thanks.
There is no Yii based solution for handling UI-Widgets with AJAX right now and will never come.
Probably, this will never happen again in Yii2. The main Problem is about your missing JS-Ressources and Binding (as you know already). Yii will generate those codes (which you are missing) within the layout process, which is not called on "AJAX"-Requests. Don't try to put in your JS-Ressources by yourself. Yii generated JS-Cods are realy tricky ... and not that easy to handle manualy. This will come up with a lot of problems.
My solution: I dont use any of the "UI"-Features included in Yii. They come along with a lot of problems (Ajax, Multiple announces, etc.). Its not hard to write that features yourself or using jQueryUI.
Take a look at the Tab feature and try write it yourself .. and be happy ! :)

Categories