Yii2: Get selected rows data from gridView checkbox columns into controller - javascript

I've view page(index.php) in my Yii2 project, and I'm using Kartik gridView for showing the data
This the view from index.php:
On the right side of view, I've a checkbox column.
And I've an Export button.
I want to export the selected name (selected by checkbox) into name.txt file.
I've finally make the export function, but I don't know how to get the selected data from view into controller.
I've try suggestions that I got from many forums, for example:
I put this javascript code in my view index.php:
<script>
function getRows(){
var keys = $('#grid').yiiGridView('getSelectedRows');
$.post({
url: FakturOutController / exportAction,
dataType: 'json',
data: {keylist: keys},
success: function(data) {
alert('I did it! Processed checked rows.')
},
});
}
and set the export button like this:
<p>
<button type="button" onclick="getRows()" class="btn btn-success">Export</button>
</p>
But I got nothing, the button didn't showed any action/reaction when clicked.
This is the gridView code in index.php:
`<?php Pjax::begin(); ?>
<?=
GridView::widget([
'dataProvider' => $dataProvider,
'tableOptions' => ['class' => 'table table-hover'],
'columns' => [
['class' => 'yii\grid\SerialColumn',
'header' => 'No',
],
[
'label' => 'Name',
'value' => function($data) {
return $data->name;
}
],
['class' => '\kartik\grid\CheckboxColumn'],
],
'toolbar' => [
['content' =>
Html::a('<i class="glyphicon glyphicon-repeat"></i>', ['index'], ['data-pjax' => false, 'class' => 'btn btn-default', 'title' => 'Reset Grid'])
],
'{export}',
'{toggleData}'
],
'panel' => [
'heading' => '<i class="glyphicon glyphicon-align-left"></i> <b>Data</b>',
'before' => '', //IMPORTANT
],
]);
?>
<?php Pjax::end(); ?>
<?=
Html::a('<i class=" glyphicon glyphicon-export"></i> Export', ['export', 'userId' => $userId], ['class' => 'btn btn-success']);
?>`
Any help would be appreciated. Thanks

By inspect element on checkbox column you can find name of row ( checkbox name ). it contain id as value.
from that you can find how many rows are selected.
in my case i get 'selection[]' in checkbox name.
ex.
<input type="checkbox" class="kv-row-checkbox" name="selection[]" value="1">
i write jquery code to get selected rows below.
<script>
function getRows()
{
var strvalue = "";
$('input[name="selection[]"]:checked').each(function() {
if(strvalue!="")
strvalue = strvalue + ","+this.value;
else
strvalue = this.value;
});
// strvalue contain selected row by comma separated
$.post({
url: FakturOutController / exportAction,
dataType: 'json',
data: {keylist: keys},
success: function(data) {
alert('I did it! Processed checked rows.')
},
});
}
</script>

Related

Yii2 Dynamic Form Select2 Change Event not working from second index

I was trying to create a dynamic form for one of my project. I initialized a ajax request to retrieve value for a field.
<div class="row">
<div class="col-md-4">
<?php echo $form->field($modelAddress, "[{$i}]rt_item")->widget(Select2::class, [
'data' => $invListData,
'options' => ['placeholder' => '--Select Request Type--', 'class' => 'form-control'],
'pluginOptions' => [
'allowClear' => true
],
'pluginEvents' => [
'select2:select' => 'function(params) {
var itemVal = $(this).val();
var attrID = $(this).attr("id").replace(/[^0-9.]/g, "");
$.ajax({
"url" : "units",
"type" : "post",
"data" : {itemID: itemVal},
success: function (data) {
console.log(data);
console.log(attrID);
$("#reqitems-"+attrID+"-rt_unit").val(data);
},
error: function (errormessage) {
//do something else
alert("not working");
}
});
}',
],
]); ?>
</div>
<div class="col-sm-4">
<?= $form->field($modelAddress, "[{$i}]rt_unit")->textInput(['maxlength' => true, 'readOnly' => 'true']) ?>
</div>
The ajax is working perfectly in the first index of the dynamic form. But unfortunately from the send index, nothing is happening. I checked couple of questions & answers in stackoverflow for the situation, but everything failed.
Can anyone help me to find a solution?
Hi found a solution in an alternative way using jquery.
Since the elements are dynamically loaded, we need dynamically generate via AJAX or something similar the following input element. I removed the pluginEvent and initialized a new class for dynamic field.
<?php echo $form->field($modelAddress, "[{$i}]rt_item")->widget(Select2::class, [
'data' => $invListData,
'options' => ['placeholder' => '--Select Request Type--', 'class' => 'reqItem form-control'],
'pluginOptions' => [
'allowClear' => true
]); ?>
Then manually I wrote jquery script to read the element.
<script>
$(document).on("change", ".reqItem", function() {
var itemVal = $(this).val();
var attrID = $(this).attr("id").replace(/[^0-9.]/g, "");
$.ajax({
"url": "units",
"type": "post",
"data": {
itemID: itemVal
},
success: function(data) {
console.log(data);
console.log(attrID);
$("#reqitems-" + attrID + "-rt_unit").val(data);
},
error: function(errormessage) {
//do something else
alert("not working");
}
});
});
But still I am working to find the appropriate solution using Yii.

Html::dropDownList depending Yii2

I have a problem to connect two select. I would like the choice of a select filters the search of the second select statement.Both select take data from their tableDB but are not influenced each other. Can someone help me?
my first select customers take data from db table customers:
<?=
Html::dropDownList('userlist', [],
ArrayHelper::map(Customers::find()->where('id',['company_id' =>
'name'])->orderBy('name')->all(), 'id', 'name'),
['prompt' => 'Select a User ...',
'class' => 'form-control',
'style' => 'width: 100%;']);
?>
my second select offers take data from db table offers:
<?=
Html::dropDownList('offerslist', [],
ArrayHelper::map(Offers::find()->where('customer_id',['company_id'
=> 'offers_n'])->orderBy('customer_id')->all(),
'id','offers_n','customer_id'),
['prompt' => 'Select a Offert ...',
'onchange' => 'change_user_list(this.value)',
'class' => 'form-control',
'style' => 'width: 100%;']);
?>
This is my function js:
function change_user_list(company_id)
{
$.ajax({
url: "<?= \yii\helpers\Url::to(['offers/userlist'])?>",
type: 'get',
data: {
company_id: company_id
},
success: function (data) {
document.getElementsByName('userlist')[0].innerHTML = data;
}
});
}
this is my actionFucntion in the controller:
public function actionUserlist($company_id)
{
if (Yii::$app->request->isAjax) {
$userlist = ArrayHelper::map(Customers::find()-
>where(['company_id' => $company_id])->orderBy('name')->all(),
'id', 'name');
$string = "<option value>Select a Users</option>";
foreach($userlist as $id => $name) {
$string .= "<option value=".$id.">".$name."</option>";
}
return $string;
}
}

Pass javascript value to a form action URL in Yii2

I'm trying to put a value from javascript into a form action in Yii2
is it possible?
More specifically I need to make a URL change for each option that is selected in a dropdownList.
form in views/site.php
$form = ActiveForm::begin([
'id' => 'form',
'method' => 'POST',
'action' => Url::to(['programas/'.Tours::findOne(['pk' => ])->programa]),
]);
<?= $form->field(new \app\models\Tours(), 'nombre')->dropDownList([],
[
'prompt' => 'Programa',
'id' => 'child1_child2',
'onchange' => 'updateValue(this.value)',
]
)->label(false); ?>
Js file
function updateValue(val){
x = document.getElementById("test").value;
// document.getElementById("form").action = "programas/";
}
So, I rescue the value from the selected option with JS but I need to put it in here 'pk' => 'value'
where value is the #child1_child2 selected option value.
'action' => Url::to(['programas/'.Tours::findOne(['pk' => ])->programa])
Thanks for the help.
You can use one of the following approach with some modification:
//pk => programa
$data = [
1 => 'programa1',
2 => 'programa2',
3 => 'programa3',
];
1) Use JS
<?= $form->field(new \app\models\Tours(), 'nombre')->dropDownList($data, ['prompt' => 'Programa'])->label(false); ?>
JS
$this->registerJs('
$("#dropdownID").change(function() {
var text = $("#dropdownID option:selected").text();
$("#formID").attr("action", "/pathtoproject/programas/" + text);
});
', \yii\web\View::POS_END);
2) Use Ajax Call
<?= $form->field(new \app\models\Tours(), 'nombre')->dropDownList($data, [
'prompt' => 'Programa',
'onchange'=> '$.get( "'.Url::toRoute('get-action').'", { id: $(this).val() } )
.done(function( data ) {
$("#formID").attr("action", data);
}
);'
])->label(false); ?>
Controller
public function actionGetAction($id)
{
$name = Tours::findOne(['pk' => $id])->programa];
echo \yii\helpers\Url::to(['programas/'.$name]);
}

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.

want to select user from onchange of dropdown list of department in cakephp?

i have two tables user and department where department has two fields id and name i want to create a view so that when someone selects a department name from the dropdownlist the user's name of all in that department show in another dropdownlist using AJAX and How to call that in controller
<script>
jQuery(document).ready(function ($) {
//jQuery('#searchTable').dataTable();
$('#department_id').change(function () {
jQuery('#user').empty();
var data2 = {};
data2['department_id'] = jQuery(this).val();
var json = JSON.stringify(data2);
jQuery.ajax({
type: "POST",
url: "/AjaxRequests/name",
data: json,
dataType: "json",
success: function (response) {
var app = "<option value>All</option>";
jQuery('#user').append(app);
jQuery.each(response, function (i, text) {
jQuery('#user').append(jQuery('<option></option>').val(i).html(text));
});
}
});
});
</script>
this is the script i am using
and in view the department dropdown is like this
<?php echo $this->Form->input('department_id', array('onChange' => 'showFields(this.value)', 'class' => 'form-control-custom', 'id' => 'department_id', 'type' => 'select', 'label' => true, 'label' => 'department:', 'options' => $departments, 'empty' => 'Select A Department', 'required' => 'false'))
?>
Anyone please help me with this ajax and also the controller
According to your code, can u try to replace 'id' => 'department' with 'id' => 'department_id' . Cause it's seen here you are using department_id as selector but your department_id id as not declared in dropdownlist. Here you declared department as ID. So selector is not found. So Just replace 'id' => 'department' with ''id' => 'department_id'', Hope it can be helpful to you.

Categories