I have one modal in one form and two different button to call this modal.
This are my two buttons
<?= Html::button('Search Ticket', [
'value' => Yii::$app->urlManager->createUrl('/ticket-timbangan/list'),
'class' => 'btn btn-primary showModal',
'id' => 'BtnModalTicketList',
'title' => 'List Ticket Timbangan',
]) ?>
<?= Html::button('Search Contract', [
'value' => Yii::$app->urlManager->createUrl('/contract/list'),
'class' => 'btn btn-primary showModal',
'id' => 'BtnModalContractList',
'title' => 'List Contract',
]) ?>
Modal will show list of tickets or contracts to be selected by user to fill new data (as reference) and the return is Json::encode.
my modal code:
Modal::begin([
'headerOptions' => ['id' => 'modalHeader'],
'id' => 'modal',
'size' => 'modal-lg',
'closeButton' => [
'id'=>'close-button',
'class'=>'close',
'data-dismiss' =>'modal',
],
'class' => 'style=width:auto',
'clientOptions' => [
'backdrop' => false, 'keyboard' => true
]
]);
echo "<div id='modalContent'></div>";
Modal::end();
and in the script for showing up the modal
$(document).on('click', '.showModal', function(){
if ($('#modal').hasClass('in')) {
$('#modal').find('#modalContent')
.load($(this).attr('value'));
document.getElementById('modalHeader').innerHTML = '<h4>' + $(this).attr('title') + '</h4>';
} else {
$('#modal').modal('show')
.find('#modalContent')
.load($(this).attr('value'));
document.getElementById('modalHeader').innerHTML = '<h4>' + $(this).attr('title') + '</h4>';
}
});
script in the action list would be like this after user click selected row
$(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);
$('#pengirimanproduksi-ticket_id').val(data.id);
$('#pengirimanproduksi-vehicle_id').val(data.vehicle_id).trigger('change');
$('#pengirimanproduksi-item_id').val(data.item_id).trigger('change');
$('#pengirimanproduksi-bruto_tbg').val(data.bruto);
$('#pengirimanproduksi-tara_tbg').val(data.tara);
$('#pengirimanproduksi-remark').val(data.remark);
});
$('#modal').modal('hide');
});
the issue is when user click first button let's say ticket button to show up modal contains list of tickets to be selected. after click select, it was OK. but if user click second button let's say contract button to show up modal contains list of contracts to be selected and select one data. after event close the modal, it would execute script from first modal (which is ticket).
how to prevent this?
Thanks in advance
Related
This is my form field.
As can see, there is a div tag with details id right below the form field. I wanted to print the content inside the div tag out whenever I select the contact.
$url2 = yii\helpers\Url::toRoute('op-client/contact');
$this->registerJs($this->render('script2.js'), \yii\web\VIEW::POS_READY);
$form->field($model, 'contact_id')->widget(Select2::classname(), [
'data' => $getcontact,
'language' => 'en',
'options' => ['placeholder' => 'Select'],
'pluginOptions' => [
'allowClear' => true
],
'pluginEvents' =>
[
'change' => 'function()
{
var contactid = $(this).val();
getDetails(contactid);
"'.$url2.'"
}',
],
]).'
<div id="details">
</div>
Script2.js
function getDetails(contactid,url2)
{
var csrfToken = $('meta[name="csrf-token"]').attr("content");
console.log(contactid);
$.ajax({
type:"POST",
cache:false,
url:url2,
data:{contactid:contactid, _crsf:csrfToken},
success:function(data){
$("#details").html(data);
//document.getElementById("details").innerHTML = data;
},
})
}
Controller
public function actionContact()
{
$request = Yii::$app->request;
$contact = $request->post('contactid');
$contacts =OpContact::find()
->where(['id'=>$contact])
->one();
echo $contacts->name;
}
The problem seems like I cant print out the contact name. I can get the correct contact id but I cant print out the name inside the div tag, it just show blank onchange. Is there anything wrong with my calling method? Thanks
I'm creating a module with differents forms. I have some forms which are modal forms using ctools.
On one of these modal forms i made a button to open a pdf on a new tab in my browser but it doesn't work.
I have a AJAX error.
This is my code:
function liste_apprenant_partenaire($js){
if ($js) {
ctools_include('ajax');
ctools_include('modal');
ctools_add_js('ajax-responder');
$form_state = array(
'ajax' => TRUE,
);
$output = ctools_modal_form_wrapper('liste_apprenant_partenaire_form', $form_state);
if (!empty($form_state['ajax_commands'])) {
$output = $form_state['ajax_commands'];
}
print ajax_render($output);
drupal_exit();
}
else {
return drupal_get_form('liste_apprenant_partenaire_form');
}
}
function liste_apprenant_partenaire_form($form, &$form_state){
$form['pv-button'] = array(
'#id' => 'pv-button',
'#type' => 'submit',
'#value' => 'PV',
'#submit'=>array('pv_apprenant_partenaire_button_form_submit'),
'#attributes' => array('onclick' => 'target="_blank";return true;'),
);
return $form;
}
function pv_apprenant_partenaire_button_form_submit(&$form, &$form_state){
require_once("sites/all/modules/print/lib/dompdf/autoload.inc.php");
$node_session=node_load($_SESSION['nid_session']);
$type_formation=$node_session->field_type[LANGUAGE_NONE][0]['value'];
$test=file_get_contents('sites/all/modules/multi_example/test.html');
$test=str_replace('+type_formation',"$type_formation",$test);
$dompdf = new Dompdf();
$dompdf->loadHtml($test);
$dompdf->render();
$dompdf->stream('my.pdf',array('Attachment'=>0));
}
When i put the path of the node in my browser, it's worked fine because the form appears normally not as a modal form.
But i research the same result using a modal form. So i think there is a problem with AJAX but i don't find the real solution.
do not use button type submit
use form item type link then if you need this link look like button then you can style this as a button
use like this in the form
$form['my_module_custom_link'] = array(
'#type' => 'link',
'#title' => 'PDF',
'#href' => "/my/hello",
'#attributes' => array(
'target' => '_blank',
),
it should display a link inside the form then style it as you need
Hi guys i have a gridview like below
and i want to get the 'user_id' of the checked column
how can i do that???
I could easily get the checked column id but i dont know how to get data of those checked column in gridview
i want to get it via javascript so that i can pass it to service
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'showOnEmpty'=>true,
'columns' => [
['class' => 'yii\grid\CheckboxColumn'],
[
'attribute' => 'event_id',
'label' => 'Event Title',
'value' => 'event.title'
],
[
'attribute' => 'user_id',
'label' => 'Email',
'value' => 'users.email',
],
'user_type',
],
]);
?>
and here is my javascript to get ids of checked column
jQuery(document).ready(function() {
btnCheck = $("#send");
btnCheck.click(function() {
var keys = $("#w0").yiiGridView("getSelectedRows");
}
});
Let me tell you the flow of this
On homepage is a gridview like this
Now user will click on that small user sign and that will open the page you can see below
Thats when i want to send messages to all selected users
Because in my case title is from different table and name and email are from different table so i want ids of user table
For that i want user_id but i am getting some random values
What can i do here???
I tried this but its returning some random string
public function search($params)
{
if(!isset($_GET['id'])){
$id='';
}
else{
$id=$_GET['id'];
}
$query = Checkin::find()->where(['event_id'=> $id]);
$query->joinWith(['event', 'users']);
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if (!$this->validate()) {
return $dataProvider;
}
$query->andFilterWhere([
'id' => $this->id,
'created_date' => $this->created_date,
'created_by' => $this->created_by,
'updated_date' => $this->updated_date,
'updated_by' => $this->updated_by,
]);
$query->andFilterWhere(['like', 'user.email', $this->user_id]);
$query->andFilterWhere(['like', 'user_type', $this->user_type]);
$dataProvider->keys ='user_id';
return $dataProvider;
}
Update your DataProvider set $dataProvider->keys ='userId' then you will able to get all keys of user_id
data-id of GridView and get allSelectedColumns
You need to just replace this code
['class' => 'yii\grid\CheckboxColumn'],
with below code
[
'class' => 'yii\grid\CheckboxColumn',
'checkboxOptions' => function($data) {
return ['value' => $data->user_id];
},
],
I have a GridView displaying employee payslips, and beside each of their names are check boxes. Refer to the picture below:
As you can see, I also have a drop-down list. I set it in my jQuery to select the last child of the list which is my case, the April 10, 2015 - April 16, 2015 option. On page load, I can see this page (photo above) with those check boxes. I had a problem with the check boxes since when I click the header check box, it should select all of the check boxes below it. But it's not. Now, when I tried selecting another option in the drop-down list, here's what I get:
The style of the check boxes changes. And now, when I check the header check box, it's already working, selecting every check boxes below.
Here's how I display the drop-down list:
echo Select2::widget([
'name' => 'period',
'data' => $period,
'options' => [
'placeholder' => 'Select period',
'id' => 'period',
'style' => 'width: 400px; height: 34px;'
],
'pluginOptions' => [
'maximumInputLength' => 10,
],
]);
GridView:
<?php \yii\widgets\Pjax::begin(['id' => 'employee']); ?>
<?php
echo GridView::widget([
'dataProvider' => $dataProvider,
//'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
['class' => 'yii\grid\CheckboxColumn',
'options' => ['class' => 'icheckbox_minimal',]
],
'fname',
'lname',
'totalEarnings',
'totalDeductions',
'netPay',
[
'label' => 'Action',
'content' => function ($model, $key, $index, $column) {
if ($model->netPay != null) {
return Html::a('View Payslip', ['view' , 'id' => $model->payslipID], ['class' => 'btn btn-success']);
}else{
return Html::a('Create Payslip', ['create-new', 'id' => $model->user_id], ['class' => 'btn btn-warning']);
}
}
]
],
]);
?>
<?php \yii\widgets\Pjax::end(); ?>
Script:
<script>
$(document).ready(function(){
$("#period option:last-child").attr('selected', 'selected');
$("#period").change( function()
{
var period = $('#period').val();
if(period != 0){
$.ajax({
url: 'index.php?r=payslip/periods',
dataType: 'json',
method: 'GET',
data: {id: period},
success: function (data, textStatus, jqXHR) {
$.pjax.reload({container:'#employee'});
//alert(data.start);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('An error occured!');
alert('Error in ajax request');
}
});
}
}
);
})
</script>
My question is, how do I preserve/maintain the style of the check boxes? And why does it change in style? And why are the styled check boxes not working?
Your checkboxes are changed with javascript to look like that.
You have 2 problems:
1) your "check all" function works just fine, you just need to refresh the status of the checkboxes afterwards. It works like this: when you click on the div that replaces the checkbox then the checkbox gets changed under it. Your problem is that you check it with the scripts so you need to trigger the div that sits on top of it to change too.
2) because you use pjax your page DOM gets changed. However because you probably change the checkboxes on "onload" of the page the new checkboxes remain unstyled. You need to run the function that changes them again after the pjax call.
I am trying to get the IDs of all the selected check boxes in yii using JAVASCRIPT. Now i am able to get only the first element ID. Can anyone please suggest the correct code to get all the check box ID.
My View:
<input type="button" value="Multiple Host Date Entries" onclick="act();" />
<div id="grid"></div>
<?php
//zii.widgets.grid.CGridView bootstrap.widgets.TbExtendedGridView
$obj=$this->widget('bootstrap.widgets.TbExtendedGridView', array(
'id'=>'host_grid',
'dataProvider'=>$dataProvider,
'type' => 'striped bordered',
//'filter' => $model,
//'type' => 'striped bordered condensed',
//'summaryText' => false,
////'afterAjaxUpdate'=>'\'changeTRColor()\'',
//'itemView'=>'_view',
'columns'=>array(
array(
'id' => 'selectedIds',
'class' => 'CCheckBoxColumn',
'selectableRows'=>2,
'value' => '$data->host_id',
'checkBoxHtmlOptions' => array('name' => 'idList[]'),
),
array( // display 'create_time' using an expression
'name'=>'host_name',
'value'=>'$data->host_name',
),
array(
'name'=>'host_serviceid',
'value'=>'$data->host_serviceid',
),
array(
'name'=>'status',
'value'=>'$data->status',
),
array(
'class'=>'CButtonColumn',
'template'=>'{edit_date}{update}{delete}',
'htmlOptions'=>array('width'=>'95px'),
'buttons' => array(
'update'=> array(
'label' => 'Update',
'imageUrl' => Yii::app()->baseUrl.'/images/icons/a.png',
),
'delete'=> array(
'label' => 'Delete',
'imageUrl' => Yii::app()->baseUrl.'/images/icons/d.png',
),
'edit_date' => array( //the name {reply} must be same
'label' => 'Add Date', // text label of the button
'url' => 'Yii::app()->createAbsoluteUrl("NimsoftHostsDetails/View", array("id"=>$data->host_id))', //Your URL According to your wish
'imageUrl' => Yii::app()->baseUrl.'/images/icons/m.png', // image URL of the button. If not set or false, a text link is used, The image must be 16X16 pixels
),
),)
),
))
;
?>
I must select some check boxes and click on multiple host date entries button to go to the specific controller.
My JavaScript:
function act()
{
var idList=$("input[type=checkbox]:checked").serializeArray();
var jsonStr = JSON.stringify(idList);
/* Object.keys(idList).forEach(function(key) {
console.log(key, idList[key]);
alert(idList[key]);
});*/
var a=$("input[type=checkbox]:checked").val();
alert(a);
if(idList!="")
{
if(confirm("Add Dates for multiple hosts?"))
{
var url='<?php echo $this->createUrl('Nimsoft/Date_all',array('idList'=>'val_idList')); ?>';
url=url.replace('val_idList',jsonStr);
//url=url.replace('val_idList',json_encode(idList));
//alert(url);
window.open(url);
/*$.post('Date_all',idList,function(response)
{
$.fn.yiiGridView.update("host_grid");
});*/
}
}
else
{
alert("Please Select atleast one host");
}
}
I need to pass the IDs to NIMSOFT controller so that I can have a for loop to process each one of those.
you can retrieve the checked column in client side (javasctipt):
var idArray = $(gridID).yiiGridView('getChecked', columnID);
// or
$.fn.yiiGridView.getSelection(gridID);
For all checked row ids we use this
var id = $.fn.yiiGridView.getChecked("your-grid-id", "selectedIds"); // array of seleted id's from grid