I am making a gridview in yii and my problem is that if i click select all checkbox and i go to next grid then again i click on select all after that i should get 20 values. but i am getting only 10 values which is getting from current grid. how can i get all selected checkbox value in my controller?
here is my view
<form action="<?php echo Yii::app()->createAbsoluteUrl("emails/getEmails"); ?>" method="post">
<?php
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'professional-master-grid',
'dataProvider'=>$model->search($status),
'filter'=>$model,
'selectableRows' => 2,
'afterAjaxUpdate' => "function(id,data){
$('.select-on-check').each(function(){
if(globalselected.indexOf($(this).val()) < 0){
$(this).prop('checked',false);
}else{
$(this).prop('checked',true);
}
});
}",
'beforeAjaxUpdate' => "function(id,data){
if(typeof globalselected == 'undefined') {
globalselected = [];
}
selected = $('.select-on-check:checked').map(function(i) {
return $(this).val();
}).get();//.join(',');
notselected = $('.select-on-check:not(:checked)').map(function(i) {
return $(this).val();
}).get();//.join(',');
for(i=0; i < selected.length; i++){
if(globalselected.indexOf(selected[i]) < 0){
globalselected.push(selected[i]);
}
}
for(i=0; i < notselected.length; i++){
if(globalselected.indexOf(notselected[i]) >= 0)
globalselected.splice(globalselected.indexOf(notselected[i]), 1);
}
}",
'columns'=>array(
/*'id',*/
array(
'header'=>'SN.',
'value'=>'$this->grid->dataProvider->pagination->currentPage * $this->grid->dataProvider->pagination->pageSize + ($row+1)',
),
array(
'class' => 'CCheckBoxColumn',
'selectableRows' => 2,
'checkBoxHtmlOptions' => array(
'name' => 'nos[]','class'=>'select-on-check','id'=>'example-check-boxes',
'type'=>'raw'
),
'value'=>'$data->id',
),
array(
'header'=>'Center name',
'value'=>'urldecode($data->center_name)',
'name'=>'center_name',
'sortable'=>FALSE,
),
array(
'header'=>'Fitness Center Type',
'value'=>'#$data->getRelated("fitnesscenter")->fitnesscenter_type',
'name'=>'fitnesscenter',
'sortable'=>FALSE,
),
array(
'header'=>'City',
'value'=>'#$data->getRelated("city_id")->city_name',
'name'=>'city_id',
'sortable'=>FALSE,
),
array(
'header'=>'Locality',
'value'=>'#$data->getRelated("locality")->locality',
'name'=>'locality',
'sortable'=>FALSE,
),
),
));
?>
<input type="submit" class="btn btn-primary" id="submit" value="submit" />
</form>
this is my controller
var_dump($_POST['nos']);
Why do you want to keep selected data between pages? I personally don't like that but anyways.
I see that you did a javascript implementation that uses a variable where it keeps all the selected ids.
I can see it saves the ids before ajax updating (before changing page) and that it also restores the already selected ones when coming back to the previous page.
But you might be missing to bind a event on clicking any of the checkboxes to also add them to this javascript variable. I would put the code in beforeAjaxUpdate to a separate js function outside. Then call it from here and also call it in click event of every checkbox. Hmm I think with only calling it from the click event would be enough.
Also I can see that selectableRows is set to 2, should be removed I guess.
And finally, I would create a hidden field named "globalselected" and after every time you alter the globalselected js array I would convert it toString and put it as value of the hidden field.
Then in the controller you would look for $_POST['globalselected'].
Related
I've inherited a piece of code from an old developer and currently trying to figure out the method behind how it submits.
I'm currently trying to get a quick fix in place where I hide one of his fields to get the form submitting, the issue I'm having is that I can't seem to set the dropdownlist to a default value, which should be United Kingdom, with the id 826 in the database.
echo CHtml::ActiveDropDownList($address, 'country_id', CHtml::listData(Country::model()->findAll(), 'id', 'name', 'continent'), array(
'class' => 'col-md-5 hidden',
'prompt' => 'Select Country',
'label' => 'something here',
'ajax' => array(
'type' => 'POST',
'url' => CController::createUrl('/user/UpdateRegions'),
'dataType' => 'json',
'data' => array('country_id' => 'js:this.value', 'YII_CSRF_TOKEN' => Yii::app()->request->csrfToken),
'success' => 'function(data) {
$("#Address_country_region_id").html(data.country_id);
$("#Address_country_region_id").removeClass(\'hidden\');
if($("#venue_id").val() === "") {
$("#Address_country_region_id").addClass(\'hidden\');
}
}',
)));
$path = CController::createUrl('/admin/user/UpdateRegions');
$id = $address->id;
// On Load
Yii::app()->clientScript->registerScript('ready', '
$.ajax({
type: \'POST\',
dataType : \'json\',
data: {\'country_id\': $(\'#Address_country_id\').val(), \'update_id\' : "' . $id . '"},
url: "' . $path . '",
success: function(data){
$(\'#Address_country_region_id\').html(data.country_id);
}
})
');
How do I get this dropdownlist pointing towards the country_id of 826 as the page loads so I can hide the field and pass the validation of the form.
regards.
this code you pasted does this:
the first part renders a dropdown which does an ajax request on change to /user/UpdateRegions to fill the dependent dropdown for the regions.
the second part does also an ajax request when the page is "ready". So that the region select is filled when the page is ready.
Your script should output the id 826 if you printout the current set id.
If not the value isn't correctly set to the address model.
echo $address->country_id;
If you want to set the default value you can do this at multiple places. e.g. in the controller 'before' the actual submitted value is set or in the model code itself (depends on your code e.g. if you have an additional form model which is extended from your activerecord model).
The correct line in your controller could be before something like this:
$address->country_id= 826;
before one of these lines in your controller
$address->attributes=Yii::app()->request->getQuery(get_class($address));
or
$address->attributes=Yii::app()->request->getPost(get_class($address));
or
$address->attributes=$_POST['address']; // or $_GET
If you have difficulties to find the correct position post some controller code.
I guess you could find some help also here
Yii 1.1: An Easy Solution for Dependent dropDownList Using AJAX
To set default value for $address model, put
$address->country_id = Yii::app()->request->getParam(get_class($address).'[country_id]', 816);
before
echo CHtml::ActiveDropDownList($address, 'country_id', CHtml::listData(Country::model()->findAll(), 'id', 'name', 'continent'), array(
I have a search form. I would like to pagination the result.
$criteria something like this:
if($_POST["tipus"] != 4){
$criteria->compare('t.tipus',$_POST["tipus"],true);
}
if($_POST["varos"] != 0){
$criteria->compare('`apartman`.`city`', $_POST["varos"], true);
}
if($_POST["ferohely"] != 0){
$criteria->compare('t.ferohely', $_POST["ferohely"], true);
}
My dataprovider:
$dataProvider= new CActiveDataProvider('UserAndApartman', array(
'criteria'=>$criteria,
'sort'=>array(
'defaultOrder'=>'t.id DESC',
),
'pagination'=>array(
'pageSize'=>2,
),
));}
$this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'kereses_eredmenyek_view',
));
So if i click on the second page, the post doesn't come again. How can i post it automatic?Can i get the $dataprovider with pagination?
You're using $_POST, the $_POST['tipus'] and other data is lost when
you're navigating to the next page, since you're not posting it to
page 2, 3 etc. You can do two things:
Store the $_POST['tipus'] in a session, so the next page 'knows' what year it has to use.
Store it in the url as a $_GET parameter, so instead of $_POST['tipus'] use $_GET['tipus']. When you navigate to page 2, the $_GET['tipus'] is available in the url on the next page.
The last one is the easiest one i think, and that's how i usually use it.
IF you use the get method, change the CActiveForm line to this:
<?php $this->beginWidget('CActiveForm', array(
'id'=>'fromid',
'method' => 'get'
)); ?>
Ive spent several hours trying to resolve an issue with very limited experience with jQuery which is not helping me.
I am wanting to search a database for a list of results using a few input fields and then a submit button, when you click submit the values are passed to a .php script which returns the results and these are displayed in a table within a div container which works perfect.
Each record is then displayed in its own row within the table, with columns for different data.
record number name town etc
What i want is for the record number to be a click link of some kind, which when clicked, it then passes that value and does a different mysql request displaying that unique records data in more detail in a different div container. This is the part i cant get to work as i believe its something to do with BINDING, or the .ON which i dont really know anything or understand how it works, as my experience is very limited.
I have provided some sample code which consists of two files, jQuery.php and db.php, db.php is just simulating a database lookup for now (crude i know), to make it easier to show my code and what i am trying to do.
if you run jQuery.php and either enter a town (sheffield,rotherham) followed by click "get data" you get a refined list of results, if you just click get data you get all the results, you will see each results as a 4 dig ID Number, what i want to happen here is when you click that number it then loads just that record in a different div container, but its not working due to the dynamic content as i have read but don't understand.
You will see i have made an example of the reference number 1005 at the top of the page, and if you click on this, it loads that unique record fine, but i just can't get it to work with the ones in the table.
jquery.php
<script type="text/javascript" src="https://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".click").click(function() {
var recordid = $(this).attr("id");
$('#2').load("db.php?id=" +recordid);
});
$("#get").click(function() {
var town = $("#town").val();
$('#1').load("db.php?town="+town
);
});
});
</script>
OUTSIDE OF DYNAMIC HTML RECORD ID : - <a class = 'click' id = '1005'>1005</a><br>
<br>
Town <input type="textbox" id="town" ><br>
<button id="get">Get Data</button>
<br>
----<br>
*<div id="1" name='records_all'></div>
----<br>
*<div id="2" name='record_unique'></div>
----<br>
db.php ( crude code to simulate a db lookup, just for purpose of this problem )
<?php
$id = $_GET['id'];
$town = $_GET['town'];
echo "<pre>";
$data[]= array('id' => '1001', 'town' => 'sheffield', 'street' => 'national av', 'name' => 'neil');
$data[]= array('id' => '1002', 'town' => 'rotherham', 'street' => 'maple drive', 'name' => 'steve');
$data[]= array('id' => '1003', 'town' => 'leeds', 'street' => 'poplar drive', 'name' => 'john');
$data[]= array('id' => '1004', 'town' => 'rotherham', 'street' => 'exchange st', 'name' => 'claire');
$data[]= array('id' => '1005', 'town' => 'sheffield', 'street' => 'main street', 'name' => 'sarah');
$data[]= array('id' => '1006', 'town' => 'rotherham', 'street' => 'holderness rd', 'name' => 'jo');
if ($id) {
foreach ((array)$data as $key => $value) {
if ($data[$key]['id'] == $id) {
echo $data[$key]['id']."<br>";
echo $data[$key]['name']."<br>";
echo $data[$key]['street']."<br>";
echo $data[$key]['town']."<br>";
}
}
} else {
if ($town) {
foreach ((array)$data as $key => $value) {
if ($data[$key]['town'] == $town) {
$link = "<a class = 'click' id = '{$data[$key]['id']}'>{$data[$key]['id']}</a>";
echo "{$link} {$data[$key]['town']} {$data[$key]['name']}<br>";
}
}
} else {
foreach ((array)$data as $key => $value) {
$link = "<a class = 'click' id = '{$data[$key]['id']}'>{$data[$key]['id']}</a>";
echo "{$link} {$data[$key]['town']} {$data[$key]['name']}<br>";
}
}
}
You need to use event delegation to solve this issue. Look at the jQuery docs for .on here under the "Direct and delegated events" section
Try something like
$('#1').on('click', '.click', function() {
var recordid = $(this).attr("id");
$('#2').load("db.php?id=" +recordid);
});
This will work as long as the #1 element is in the DOM when the jQuery event bindings are run. Essentially you're binding the click event to the #1 element instead of having to bind it to elements after loading them in. The jQuery docs do a good job of explaining this.
If the elements are not in the DOM at the time of their jQuery selection then the events will not be added with the way you wrote your code. However alternatively you can write your code like this
$(document).ready(function() {
$(document).on('click', '.click', function() { //this is the only thing that changed
var recordid = $(this).attr("id");
$('#2').load("db.php?id=" +recordid);
});
$("#get").click(function() {
var town = $("#town").val();
$('#1').load("db.php?town="+town
);
});
});
This code should completely replace your javascript. It creates a live listener for all future elements in the document with the class click.
Many input field and button pairs for ajax request works only for first time. After first request-response other buttons doesn't call ajax function.
There's a data grid list. Each row has a Title field (as input) with a button to call ajax function for updating this field and refresh list.
first time I click on one of the buttons everything works fine, data sends and list refresh with new data. but after this when I click on one of the buttons nothing happens , even function doesn't call.
Where I'm doing mistake?
My ajax function:
$('.titleBtn').click(function(event){
var id = $(this).attr('name');
var title = $('#' + id).attr('value');
var formAction = '".$this->createUrl('article/changeTitle')."';
$.get(formAction,{id:id,title:title},function(result){
$.fn.yiiGridView.update('article-grid');
}
);
event.preventDefault();
});
My grid list:
<?php $form=$this->beginWidget('CActiveForm', array(
'action'=>Yii::app()->createUrl($this->route),
'method'=>'get',
'id'=>'Artform',
)); ?>
<?php $this->widget('bootstrap.widgets.TbGridView', array(
'id'=>'article-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'ID',
array(
'header'=>Yii::t('labels','Title'),
'name'=>'Title',
'type'=>'raw',
'value'=> function($data) use ($model) {
return '<input type="text" id="'.$data->ID.'" value="'.$data->Title.'"><button type="button" name="'.$data->ID.'" class="titleBtn" >Update</button>';
},
),
....
),
)); ?>
//Some buttons irrelevant to this subject for submitting whole list.
<?php $this->endWidget('CActiveForm'); ?>
You could set the event using delegate
$('#Artform').delegate('.titleBtn', 'click', function() {
...
});
You need to add afterAjaxUpdate option to your TbGridView and add js code to invoke after ajax update and set your handlers.
I have CListView and inside im redering a view that has a button, when clicked it opens a CJUIDialog.
But when i go through to the next page with the page controller. The CJUIDialog content loads to the page without clicking the button.
Any idea why it's coming like that?
It'll be great if anyone can help me out.
Thanks!
Ok, Yii generate the ids for lot of controls in an automatic way, so to avoid collision with events I recommend you to take out the interaction handling out of the item view in the following way:
In the page where the CListView is generated:
$this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_post', // refers to the partial view named '_post'
'sortableAttributes'=>array(
'title',
'create_time'=>'Post Time',
),
));
$this->beginWidget('zii.widgets.jui.CJuiDialog', array(
'id'=>'dialog',
'options'=>array(
'title'=>'Dialog',
'autoOpen'=>false,
),
));
$this->endWidget('zii.widgets.jui.CJuiDialog');
In the item view page:
echo CHtml::htmlButton('Button',array('onclick' => '$("#dialog").dialog("open");'));
In case you need to do something with the data row (like using the id property of that data), you can create a custom javascript function that will receive the data when the button is clicked.
echo CHtml::htmlButton('Button',array('onclick' => 'myFunction('.$data->id.')'));
And the previous example then would be:
<?php
$this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_post', // refers to the partial view named '_post'
'sortableAttributes'=>array(
'title',
'create_time'=>'Post Time',
),
));
$this->beginWidget('zii.widgets.jui.CJuiDialog', array(
'id'=>'dialog',
'options'=>array(
'title'=>'Dialog',
'autoOpen'=>false,
),
));
$this->endWidget('zii.widgets.jui.CJuiDialog');
?>
<script type="text/javascript">
function myFunction(id) {
// you can put whatever you need inside the dialog
$("#dialog").html(id);
// open the dialog
$("#dialog").dialog("open");
}
</script>