Yii2 Checkbox Changes Style - javascript

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.

Related

Yii2 get value from Gridview button using javascript

I am new to Yii2 Framework , I have developed a module that will upload and display file uploaded from server using Yii2 advance framework. I completed the function for uploading the file , However. In my other function that need to display the file like pdf file to jquery ui dialog.My problem is I cannot get the value of the button when I click the button to display the pdf file uploaded. Thank you guys in advanced.
// Here is Gridview code in Index where my button Exist.
<?= DynaGrid::widget([
'columns' => [
['class' => 'yii\grid\SerialColumn'],
// 'ntraining_id',
'ctraining_description',
//'dtraining_datefrom',
[
'attribute'=>'dtraining_datefrom',
'filterType'=>GridView::FILTER_DATE,
'format'=>'raw',
'filterWidgetOptions'=>[
'pluginOptions'=>['format'=>'yyyy-mm-dd']
],
],
// 'dtraining_dateto',
[
'attribute'=>'dtraining_dateto',
'filterType'=>GridView::FILTER_DATE,
'format'=>'raw',
'filterWidgetOptions'=>[
'pluginOptions'=>['format'=>'yyyy-mm-dd']
],
],
'ctraining_numberhours',
'ctraining_type',
'ctraining_conducted',
//'ctraining_attachment',
[
'attribute'=>'ctraining_attachment',
'format' => 'raw',
'label' => 'View Profile',
'value' => function ($model){
return Html::a(Yii::t('app', ' {modelClass}', [
'modelClass' => $model->ntraining_id,
'header' => 'raw',
]), ['TblTrainingController/Listeaffecter'], ['class' => 'btn btn-success opener', 'id'=>'opener', 'data' => $model->ntraining_id,]);
},
],
//'id',
['class' => 'yii\grid\ActionColumn'],
],
'storage'=>DynaGrid::TYPE_COOKIE,
'theme'=>'panel-info',
'gridOptions'=>[
'dataProvider' => $dataProvider,
'id' => 'grid',
'filterModel' => $searchModel,
'panel'=>['heading'=>'<h3 class="panel-title">LEARNING AND DEVELOPMENT (L&D) INTERVENTIONS/TRAINING PROGRAMS ATTENDED</h3>'],
],
'options'=>['id'=>'dynagrid-1'], // a unique identifier is important
]); ?>
Here is javascript Code
$this->registerJs("$(function(){
$('.opener').click(function(e) {
alert(e.data);
//alert($(this).val());
e.preventDefault();
ViewPDfAttach();
});
});");
Here is the image of my interface that display null when I click the button from gridview
Call to alert(e.data); means you want to get the value of variable e from function callback.
While calling alert($(this).val()); means you want to get the value from value attribute in the element, but there's no value attribute found in yours.
Based on your element structure, if you want to get the value from data attribute, you can do this:
alert($(this).attr('data'));
If your element has structure like <a data-hello="Hello there">Click me</a>, you can alert with this one:
alert($(this).data('hello'));
See here for more informations:
JQuery .data()
JQuery .attr()

Prevent execute previous modal after click next modal

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

Yii2 Javascript fail to print

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

Symfony2 cascasing dropdown value change via ajax not accepting on submission

I have two entity dropdowns field in my symfony form. On the front end i change the option list of 2nd drop drown using ajax based on the value of first dropdown selected value. and Upon submitting the form i get the error that,
This value is not valid.
below is the code;
/**
* #ORM\ManyToOne(targetEntity="State")
* #ORM\JoinColumn(name="province_id", referencedColumnName="id")
*/
protected $Province;
/**
* #ORM\ManyToOne(targetEntity="District")
* #ORM\JoinColumn(name="district_id", referencedColumnName="id")
*/
protected $District;
and in the form,
->add('domicileDistrict','entity', [
'label' => ucwords('District'),
'class'=>'GeneralBundle\Entity\District',
'required' => true,
'mapped' => true,
'attr' => ['class' => 'form-control'],
'label_attr' => ['class' => 'control-label'],
])
->add('domicileProvince','entity', [
'label' => ucwords('Province'),
'class'=>'GeneralBundle\Entity\State',
'required' => true,
'attr' => ['class' => 'form-control select2'],
'label_attr' => ['class' => 'control-label'],
])
and on front end,
$("#profile_from_type_domicileProvince").change(function() {
var state = $('option:selected', this).val();
getDistrictByState(state);
});
function getDistrictByState(state){
var dict = {
type: "POST",
url: "{{ url('ajax_district_by_stateId') }}?id=" + state,
success: function(e) {
$("#profile_from_type_domicileDistrict option").remove();
$.each(e, function(e, p) {
$("#profile_from_type_domicileDistrict").append($("<option />", {
value: e,
text: p
}));
});
}
};
$.ajax(dict);
}
UPDATE: Add PRE_SUBMIT Event;
After suggestion form #Alsatian, I update my form and add the event as below, but nothing happens on selecting first dropdown.
$builder->addEventListener(FormEvents::PRE_SUBMIT, [$this, 'preSubmitData']);
public function preSubmitData(FormEvent $event){
$form = $event->getForm();
$data = $event->getData();
if (array_key_exists('Province', $data)) {
$state = $data['Province'];
$event->getForm()
->add('District','entity', [
'label' => ucwords('District'),
'class'=>'GeneralBundle\Entity\District',
'required' => true,
'mapped' => true,
'query_builder' => function(DistrictRepository $repository) use ($state) {
$qb = $repository->createQueryBuilder('d')
->andWhere('d.verified = :verified')
->andWhere('d.active = :active')
->setParameter('verified', true)
->setParameter('active', true);
if ($state instanceof State) {
$qb = $qb->where('d.state = :state')
->setParameter('state', $state);
} elseif (is_numeric($state)) {
$qb = $qb->where('d.state = :state')
->setParameter('state', $state);
} else {
$qb = $qb->where('d.state = 1');
}
return $qb;
},
'attr' => ['class' => 'form-control select2'],
'label_attr' => ['class' => 'control-label'],
]);
}
}
I had the same problem.
I wrote a bundle here to deal with "extensible" choice types (also entity or document) :
https://github.com/Alsatian67/FormBundle/blob/master/Form/Extensions/ExtensibleSubscriber.php
How I do it :
Hooking in the form submission process, we can access to the submitted entity by the PRE_SUBMIT FormEvent.
All submitted entity are loaded and are in $event->getData().
Then we have just to take this submitted choices as new 'choices' option for the field.
Caution :
Doing it so it will only validate that the entity submitted exist !
If only a part of the entities are possible choices you have to add a constraint to validate them.
You can also set the choices in the PRE_SUBMIT event, depending on the value of the first dropdown (instead of using all submitted entities).

How to get value of checked gridview column

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];
},
],

Categories

Resources