I want to change pagesize of listview using dropdown. please help me to find solution.
I have read many article but not able to do this. can u find where I'm making mistake
I'm using following code.
code for index.php (view)
code for dropdownlist
<?php echo CHtml::beginForm(); ?>
<?php echo CHtml::dropDownList('CategoryMst_pagesize','20',
array('10'=>'10','20'=>'20','50'=>'50','100'=>'100'
),
array('class'=>'form-control',
/*'ajax'=>array(
'type'=>'GET',
'data'=>array('pagesize'=>'js:this.value'),
'ajaxUpdate':()
),*/
));
?>
<?php echo CHtml::endForm(); ?>
code for listview
<?php $this->widget('zii.widgets.CListView',array(
'id'=>'category_list',
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
'summaryText'=>'{start} - {end} of {count} results',
));
?>
<?php
Yii::app()->clientScript->registerScript('category_update',
"$('#CategoryMst_pagesize').change(function(){
$.fn.yiiListView.update('category_list', {
data: $(this).serialize(),
}
);
});
return false;",
CClientScript::POS_READY);
?>
code in cotroller
public function actionIndex($pagesize=20)
{
$dataProvider=new CActiveDataProvider('CategoryMst',array(
'criteria'=>array(
),
'pagination'=>array(
'pageSize'=>$pagesize,
),
));
$this->render('index',array('dataProvider'=>$dataProvider));
}
You really should not be using $('#CategoryMst_pagesize').change use https://api.jquery.com/on/ instead.
Then from what I see you are not remembering the page size anywhere, after you change it 1 time, as soon as you go to another page it will revert back to what you had before. THis is how I do it:
1) First use something to remember the page size, because right now you do not. I personally recommend this one http://www.yiiframework.com/extension/esaverelatedbehavior/ as it is really, really, really good. It also remember your filters (priceless).
2) create a function for your controller that will just save the page size.
/**
* Saves the new page size for this particular model
*/
public function actionPageSize($pagesize)
{
\Yii::app()->user->setState($this->modelName() . '_pagesize', $pagesize);
}
3) create the dropdown for the pagesize, I use Select 2 but you can use a normal dropdown. same Idea
<?php $this->widget('MySelect2', array(
'name' => 'pageSize',
'data'=>array('10' => '10', '25' => '25', '50' => '50', '100' => '100'),
'options'=>array('allowClear' => false, 'minimumResultsForSearch' => 30),
'htmlOptions' => array(
'data-ajax-dropdown' => $this->createUrl('pageSize'),
'style' => 'width: 80px',
'options'=>array(
(Yii::app()->user->getState($this->modelName() . '_pagesize', Yii::app()->params['defaultPageSize']))=>array('selected'=>'selected')
))));?>
4) I autosubmit the dropdowns for the page size like you do, but I submit them to the function above not to the index page
/*==========================
AUTOSUBMIT DROPDOWNS FOR THE PAGE SIZE
==========================*/
$('#pageSize').live('change',function(e){
var element = $(this);
jQuery.ajax({
"type": "GET",
"url": $(this).attr("data-ajax-dropdown"),
"cache": false,
"data":{pagesize: $(this).val()}
})
.success(function ( response ) {
$.fn.yiiGridView.update(element.closest('.widget.table').find('div.grid-view').attr('id'));
$.jGrowl("Pagination changed", { life: 2000 });
});
});
PS: I know I should not use .live
5) In the search for the model just like you do I have
return new \CActiveDataProvider($this, array(
'criteria'=>$criteria,
'sort'=>array(
'defaultOrder'=>$this->getTableAlias(false,false) . '.name asc',
),
'pagination'=>array(
'pageSize'=> \Yii::app()->user->getState(get_class($this) . '_pagesize', \Yii::app()->params['defaultPageSize']),
),
));
Related
I'm using
PHP language , yii-1.1.13 framework and MySQL DB.
In my Views , I have this code:
Views Code of Main Page
/** Start Widget **/
$this->beginWidget('zii.widgets.jui.CJuiDialog',array(
'id'=>'dialog',
'options' => array(
'title' => 'Locations Management',
'autoOpen' => false,
'modal' => true,
'resizable' => false,
'dialogClass' => 'managelocation-dialog-class',
'show'=>array(
'effect'=>'drop',
'duration'=>500,
),
'hide'=>array(
'effect'=>'drop',
'duration'=>500,
),
),
));
/**
* Render dialog view.
*/
echo $this->renderPartial('manageLocationDialog', array(
'model' => $model,
'locationInfo' => $locationInfo,
));
$this->endWidget('zii.widgets.jui.CJuiDialog');
/**
* Filter Dialog widget
*/
$this->beginWidget('zii.widgets.jui.CJuiDialog',array(
'id'=>'filter-dialog',
'options' => array(
'title' => 'Filter',
'autoOpen' => false,
'modal' => true,
'resizable' => false,
'width' => 350,
'dialogClass' => 'location-dialog-class',
'show'=>array(
'effect'=>'drop',
'duration'=>500,
),
'hide'=>array(
'effect'=>'drop',
'duration'=>500,
),
),
));
/**
* Render the filter dialog view.
*/
echo $this->renderPartial('manageLocationFilter', array(
'filterFormloc' => $filterFormloc,
'locationInfo' => $locationInfo,
));
$this->endWidget('zii.widgets.jui.CJuiDialog');?>
Views Code of Add/Edit Dialog
<div id="action-button-div" class="row">
<?php
echo CHtml::button('Create New', array(
'id'=>'action-button',
'class'=>'submit-button',
'onclick'=>"{submitActionJs();}",
'update' =>'#filter_province_name',
));
?>
<?php
echo CHtml::button('Cancel', array(
'id'=>'cancel-button',
'onclick'=>'{$("#dialog").dialog("close");}',
));
?>
</div>
Views Code of Filter Dialog
<div id="dialog-contents-container">
<div class="row">
<div id="filter-mode-div">
<?php
echo $form->labelEx($filterFormloc, 'filter_mode', array(
'label' => 'Filter Mode',
));
?>
<div>
<?php
echo $form->radioButtonList($filterFormloc, 'filter_mode', array(
1=>'ON',2=>'OFF'),array('id'=>'filter_mode'
));
?>
</div>
</div>
<div id="reset-button-div">
<?php
echo CHtml::button('Reset Settings', array(
'id'=>'reset-button',
'onclick'=>'{$(this.form).find("textarea, :text, select").val("").end().find(":checked").prop("checked", false);$("#ManageLocationFilterForm_filter_mode_1").attr("checked",true);}',
));
?>
</div>
</div>
<div id="under-container">
<div class="row">
<div id="province_name">
<?php
echo $form->labelEx($filterFormloc, 'province_name', array(
'label' => 'Province *',
));
?>
<div>
<?php
echo $form->dropDownList($filterFormloc, 'province_name',
$locationInfo->getAllProvincesForSelection(true, 'Select Province'),
array(
'id' => 'filter_province_name',
'class' => 'selectbox',
)
);
?>
</div>
</div>
</div>
</div>
<div id="action-button-div" class="row">
<?php
echo CHtml::button('Apply Filter Settings', array(
'id'=>'action-button_2',
'onclick'=>"{submitFilterActionJs();}"
));
?>
<?php
echo CHtml::button('Cancel', array(
'id'=>'cancel-button_2',
'onclick'=>'{$("#filter-dialog").dialog("close");}',
));
?>
</div>
</div>
In my controller, below is my code:
public function actionRegisterLocation() {
$model = new ManageLocationForm;
if (isset($_POST['ManageLocationForm']))
{
$model->attributes = $_POST['ManageLocationForm'];
if (Yii::app()->request->isAjaxRequest)
{
if ($model->hasErrors())
{
$errors = '';
foreach ($model->getErrors() as $e) $errors .= implode($e).'<br>';
echo CJSON::encode(array(
'status'=>'failure',
'messages'=>$errors
));
}
else
{
$locationInfo = new LocationInfo;
if ($model->operation_mode === AdminGeneralHelper::OPERATION_MODE_UPDATE)
{
$locationInfo=LocationInfo::model()->findByPk($model->location_id);
}
$locationInfo->short_name = $model->short_name;
$locationInfo->town_name = $model->town_name;
$locationInfo->province_name = $model->province_name;
$locationInfo->save();
if ($model->operation_mode === AdminGeneralHelper::OPERATION_MODE_CREATION)
$_message = 'Create operation completed.';
if ($model->operation_mode === AdminGeneralHelper::OPERATION_MODE_UPDATE)
$_message = 'Update operation completed.';
if ($locationInfo->hasErrors())
{
$errors = '';
foreach ($locationInfo->getErrors() as $e) $errors .= implode($e).'<br>';
echo CJSON::encode(array(
'status'=>'failure',
'messages'=>$errors
));
}
echo CJSON::encode(array(
'status' => 'success',
'messages' => $_message,
));
}
exit;
}
}
else
{
echo "FALSE";
}
Yii::app()->end();
}
Below is the scenario:
I open the dialog for Adding a location. (Parameters are short_name, town, and province)
Location was Successfully added in the Grid View and DB.
I open the dialog for filter. It can only filter by Province.
When I take a look at the Dropdown lists, Location that was successfully added is not on the lists.
My question is how to update the dropdown lists of filter dialog after I successfully added a location from Add/Edit Dialog. Alternative solution is I need to refresh the browser then open the filter dialog. But it is not that user friendly. Its really a bug.
update or replace requires the response for the query to be html (see the source for CHtml::ajax() for more detail). Your query returns json. You have several options:
You can change the controller to return all the options for the dropdown as html and continue using update.
You can change the controller to return the full dropdown as html and use replace instead of update.
You can change controller to return the id and value of the newly added location and use a custom javascript function to add this option to the dropdown.
I tried the Option No.3 and its working.
Below is the working code from my Javascript file.
function submitActionJs() {
var fareCat = document.getElementById("name").value;
var newFareCat = toTitleCase(fareCat);
$.ajax({
url: 'registerFareCategory',
type: 'POST',
datatype: 'json',
data: $('form').serializeArray(),
timeout: 10000,
beforeSend: function(){
$('#dialog-msg').html('Processing...');
},
success: function(data){
var res = eval('(' + data + ')');
$('#dialog-msg').html(res.messages);
if (res.status == 'success'){
$("#message-label").html(res.messages);
$.fn.yiiGridView.update('fare-category-grid');
$("#dialog").dialog("close");
window.parent.$('#filter_name').append('<option value = "' + newFareCat + '">' + newFareCat + '</option>');
//sort fare category dropdownlist from filter dialog
$("#filter_name").html($('#filter_name option').sort(function(x, y) {
return $(x).text().toUpperCase() < $(y).text().toUpperCase() ? -1 : 1;
}));
$("#filter_name").get(0).selectedIndex = 0;
e.preventDefault();
}
},
error: function(){
$('#dialog-msg').html('Ajax Communication Error.');
}
}
);
}
Thanks #topher for your suggestion.
I'm going nuts with this. I am requesting ajax call in several places, and none of these ajax calls are working correctly lately. Today I decided to start fresh on a new section with ajax call. It's the same thing with all the other ones. It's been days that ajax data is not posting to controller - always blank.
Here is one of them. I am trying to allow users to vote up/down on click on CButtonColumn {up}{down}. This view grid "_vote.php" is generated through renderPartial using TbTabs. On renderpartial I did set to true on the last param.
Okay, next the grid. Here it is:
<?php $this->widget('bootstrap.widgets.TbGridView', array(
'type'=>'condensed',
'id'=>'vote',
'dataProvider'=>$dataProvider,
'template'=>"{items}",
'ajaxUpdate'=>true,
'columns'=>array(
array(
'class'=>'CButtonColumn',
'template' => '{up} {down}',
'buttons' => array(
'up' => array(
'label'=>'<i class="fa fa-thumbs-up"></i>',
'imageUrl'=>false,
'url'=>'Yii::app()->createUrl("prod/votecommentup", array("id"=>$data->primaryKey))',
'click'=>' function(){
$.fn.yiiGridView.update("vote", {
type:"POST",
url:$(this).attr("href"),
success:function(data) {
$.fn.yiiGridView.update(vote);
}
}',
),
'down'=> array(
'label'=>'<i class="fa fa-thumbs-down"></i>',
'imageUrl'=>false,
'url'=>'Yii::app()->createUrl("prod/votecommentdown", array("id"=>$data->primaryKey))',
'click'=>' function(){
$.fn.yiiGridView.update("vote", {
type:"POST",
url:$(this).attr("href"),
success:function(data) {
$.fn.yiiGridView.update(vote);
}
}',
),
),
),
),
)); ?>
Okay... next, the url "prod/votecommentup", which is the nearly identical as votecommentdown. Here it is:
public function actionVoteCommentUp($id){
$model = $this->loadModel($id);
if(isset($_POST['VoteThis']))
{
$model->attributes=$_POST['VoteThis'];
$model->prototype_review_id = $id;
$model->user_id = Yii::app()->user->user_id;
$model->vote = "Y";
echo CJSON::encode(array('status'=>'saved'));
}echo CJSON::encode(array('status'=>'not post')); //always give me a no post
}
I recommend testing your calls through something like Postman App for chrome. This will give you the ability to debug your API/AJAX calls independent of your view. Once you have ensured the API/AJAX is functioning correctly, you can then integrate it into the view. This allows you to decouple the debugging process and hopefully make things more transparent as to what is functional and what is not.
I'm trying my best to alter the below code so that it produces a popup box with a warning and asking for confirmation.
echo CHtml::ajaxButton(Yii::t('mc', 'Wipe Server'), '', array(
'type'=>'POST', 'data'=>array('ajax'=>'wipe', Yii::app()->request->csrfTokenName=>Yii::app()->request->csrfToken,),
'success'=>'function(e) {if (e) alert(e);}'
),
I expect adding 'confirm' => 'Wipe your server?' to add a dialog box but I'm not having much success.
I have this in ServerController:
case 'wipe':
if (Yii::app()->user->can($id, 'wipe'))
{
if (!McBridge::get()->serverCmd($id, 'run:builtin:script wipe'))
echo McBridge::get()->lastError();
}
break;
I would be grateful if anyone can point out where I am going wrong or generally point me in the right direction.
Thank you
Try this one
In Yii ajax button, beforesend function is there. Use that.
Example
<?php
echo CHtml::ajaxButton(
'Submit',
array('controlleraction'),
array(
'success' => 'js:
function (data){
}
',
'type' => 'POST',
'beforeSend' => 'js:
function(){
var r = confirm("Are you sure?");
if(!r){return false;}
}
',
));
?>
I have a Yii dropdownlist and text field, when i select the dropdown list item, this name should be displayed in textfield. I tried this concept using ajax with But it updates after page refresh only.I have pasted my code here, please look-through and suggest me how to set
textfield after every immediate selection of drop down listed item.
The following code resides protected/views/form
<td>
<?php echo $form->labelEx( ScriptQuestion::model(),'Field'); ?></td><td>
<?php echo CHtml::activedropDownList( ScriptQuestion::model(),'crm_base_contact_form_field_id',$select_field,
array(
'id' => 'send_bcfield',
'class' => 'col_165',
'ajax' => array(
'type' => 'POST',
'url' => CController::createUrl('DisplayMessage'),
'update' => '#question_editor',
'data' => array('bcfield' => 'js:this.value'),
'success'=> 'function(data) {$("#question_editor").empty();
$("#question_editor").val(data);
} ',
))
); ?>
</td>
<td>
<?php echo $form->textArea($model, 'message', array('id'=>'question_editor','maxlength'=>508, )); ?>
</td>
This is controller action:
public function actionDisplayMessage(){
$q = $_POST['bcfield'];
$model=ScriptQuestion::model()->findAll();
$sql = "SELECT name FROM crm_field WHERE crm_field_id=". $q ;
$command = Yii::app()->db->createCommand($sql);
$result= $command->queryScalar();
echo "%".$result."%";
$this->performAjaxValidation($model);
}
No need to Ajax, it's just a simple javascript/jQuery .
Just do this ( replace editor1 with your ckeditor instance name) :
<script>
$("#send_bcfield").change(function(){
var selected = $("#send_bcfield option:selected").val();
CKEDITOR.instances.editor1.setData(selected);
});
</script>
Or change your code to this :
<?php
echo CHtml::activedropDownList(ScriptQuestion::model(), 'crm_base_contact_form_field_id', $select_field, array(
'id' => 'send_bcfield',
'class' => 'col_165',
'onchange' => '$("#send_bcfield").change(function(){
var selected = $("#send_bcfield option:selected").val();
CKEDITOR.instances.editor1.setData(selected);
});',
)
);
?>
Update : I changed my code to changing a ckeditor value according to your comment below my answer.
probably you simply need to add this to CHtml::activedropDownList settings:
'onchange' => "$('question_editor').val($('#send_bcfield option:selected').text())"
I'm having troubles getting content displayed on page load using ajax. The ajax is calling the right action in the respective controller. The first part of the action code where i update the database is working fine. But the part where i'm calling renderPartial is not working.
**EDIT***
Ok here is the controller action ::
public function actionUpdateProductData() {
Yii::import('application.components.DataScraper.*');
require_once('GetProductData.php');
$productRealTime = RealTime::model()->findAll();
if (count($productRealTime) === 0) {
$symbolData = new GetProductData();
$symbolData->getAmazonProductData();
} else {
echo CJSON::encode( array(
'status' => 'OK',
'div' => $this->renderPartial('_productDataGrid', array(
'model' => $productRealTime),
true, true ),
));
}
}
The if part is working fine. But the else portion is not working.
Here is the view index.php::
<?php
/*
* Include the ajax Stock update script
*
*/
$baseUrl = Yii::app()->baseUrl;
$cs = Yii::app()->getClientScript();
$cs->registerScriptFile($baseUrl . '/js/ajaxProductDataUpdate.js');
?>
<div>
<hr>
<ul class="breadcrumb">
<li>
Home <span class="divider">/</span>
</li>
<li>
Product Info
</li>
</ul>
<hr>
</div>
<div class="span-10">
<div id="section2">
</div>
</div>
Here is the partial view file _productDataGrid.php
<?php
$this->widget('bootstrap.widgets.TbGridView', array(
'id' => 'real-time-grid',
'dataProvider' => $model->search(),
'filter' => $model,
'columns' => array(
'id',
'name',
'category',
'price'
'rating'
array(
'class' => 'bootstrap.widgets.TbButtonColumn',
),
),
));
?>
And here is the jQuery file which is making the ajax request
var productParameters = {
ajaxUpdate: function() {
$.ajax({
url: "/ProductAnalysis/index.php/realTime/updateProductData",
type: "GET",
dataType:"json",
error: function(xhr, tStatus, e) {
if (!xhr) {
alert(" We have an error ");
alert(tStatus + " " + e.message);
} else {
alert("else: " + e.message); // the great unknown
}
},
success: function(data) {
$.fn.yiiGridView.update('real-time-grid', {
data: $(this).serialize()
});
}
});
}
};
$(document).ready(function() {
productParameters.ajaxUpdate();
});
Upon loading the page /realTime/index.php i'm getting an error which says
else:
undefined
Obviously the ajax call is failing, but i don't know how will i fix it. Also in Firebug, the echo date() function in the controller is working, but the Gridview is not working.
Please provide some help on how to solve this. Let me know where i'm doing wrong. I can't seem to make any headway around this.
Thanks in advance,
Maxx
Your actionUpdateStockData() is echoing the date before the actual JSON content is encoded. As a result you're not transmitting correct JSON, and XHR will fail.
Remove the echo date ... line and you should be fine. And as you're just at it - you should add some response for the case where count(RealTime::model()->findAll()) === 0.
Well it seems that the gridview widget won't work with findall(). So i changed the dataprovider to simple model and it works now.
Here is the working code ::
public function actionUpdateStockData() {
Yii::import('application.components.DataScraper.*');
require_once('GetStockData.php');
$productRealTime = new RealTime();
if (count($productRealTime->model()->findAll()) === 0) {
$symbolData = new GetproductData();
$symbolData->getAmazonProductData();
} else {
echo CJSON::encode( array(
'status' => 'success',
'div' => $this->renderPartial('_productDataGrid', array(
'model' => $productRealTime),
true, true ),
));
}
}