I'm just learning Yii a few days ago to developer a website for company. Now i have some issue with Yii pagination and i really need your help.
Currently i can make Yii pagination. However, i need to create a button besides pagination area. Everytime, i click that button, it will call ajax to load next page or previous pages (if current page is last page).
Here is my model:
public function getListDesc()
{
$arrPlace = array(0 => '--- --- --- ---');
$criteria=new CDbCriteria;
$criteria->select='t.*,pi.path path';
$criteria->join='JOIN places_images pi ON t.id=pi.places_id';
$criteria->group = 't.id';
$criteria->compare('t.deleted', '<>1', false);
$criteria->compare('t.status',1);
$criteria->compare('outlet','Outlet 1');
$criteria->order = 't.id DESC';
return new CActiveDataProvider('Places', array(
'criteria'=>$criteria,
'pagination' => array(
'pageSize' => 2
)
));
}
Here is a part of my index page which is call that model:
<?php
$this->widget('zii.widgets.CListView', array(
'id' => 'places-list-right',
'dataProvider'=> Places::model()->getListAsc(),
'summaryText'=>'',
'pager' => array(
'header' => '',
'prevPageLabel' => '<<',
'nextPageLabel' => '>>',
),
'itemView'=>'_fea_oulet',)
);
?>
Here is _fea_oulet.php file:
<div class="place_img" id="<?=$data->id?>">
<div class="plusimage">
<a href="javascript:void(0);" onclick="randnew();">
<img alt="<?=$data->id?>" src="<?php echo Yii::app()->request->baseUrl; ?>/images/9life-show-more-images.png" style="border:none;border-radius:0;-webkit-border-radius: 0; -moz-border-radius:0">
</a>
</div>
<?php echo CHtml::image("timthumb.php?src=".$data->path."&w=294&h=294&zc=1&q=100",$data->title);?>
<div class="featitle">
<h3><span><?php
if(strlen($data->title) > 30) {
echo CHtml::encode(mb_substr($data->title,0,30,'UTF-8')) . '...';
}
else{
echo CHtml::encode($data->title);
}
?></span>
<img src="<?php echo Yii::app()->request->baseUrl; ?>/images/9life-show-more-green.png" style="border:none;border-radius:0;-webkit-border-radius: 0; -moz-border-radius:0">
</h3>
</div>
</div>
Any help are appreciates.
Thanks,
You can override CLinkPager class and use your own implementation MyLinkPager in your CListView widget's call specifying its pager property like this:
$this->widget('zii.widgets.CListView', array(
'id' => 'places-list-right',
'dataProvider' => Places::model()->getListAsc(),
'summaryText' => '',
'pager' => array(
'class' => 'MyLinkPager',
'header' => '',
'prevPageLabel' => '<<',
'nextPageLabel' => '>>',
),
'itemView' => '_fea_oulet'
));
run() method of CLinkPager is the place where pager buttons' rendering happens so you can override this method directly. Or you can override createPageButtons() method by adding your custom button to $buttons array if you want to see it along with other page buttons.
Related
I have installed xampp with upgraded php 7.4.10 version because of the higher version installed captcha is not showing image showing blank (code is blank in white background).
enter image description here
Please find below screenshot of code
Javascript of html file login.phtml
if(document.frm_login.password.value!="")
{
var hash = CryptoJS.HmacSHA256(document.frm_login.password.value, "");
$('#passwords').text('');
document.frm_login.password.value=mixUpValues(hash.toString(),
document.frm_login.keyy.value,document.frm_login.keyy1.value);
}
if(document.frm_login.vercode.value==""||document.frm_login.vercode.value==null)
{
$('#captcha-code').text('Please enter code!');
$('#vercode').focus();
return false;
}
if(document.frm_login.vercode.value!=""||document.frm_login.vercode.value!=null)
{
$('#captcha-code').text('');
}
Html code of login.phtml
<div class="form-group captcha">
<?php echo $this->form->vercode; ?>
<p><span><img src="<?php echo $this->baseUrl('cool_capcha/captcha.php'); ?>"
id="captcha" /></span>
<a onclick="document.getElementById('captcha').src='<?php echo $this-
>baseUrl('cool_capcha/captcha.php'); ?>?'+Math.random();
document.getElementById('vercode').focus();"id="change-image" class="menu4
refresh" style="cursor:pointer">
<img src="./images/refress.png" class ="refresh" id="refresh" /></a></p>
<div class="clearfix"></div><span class="require" id="captcha-code">
</span>
</div>
Forms Auth.php
$this->addElement('text', 'vercode', array(
//'label' => 'Please enter the 5 letters displayed below:',
'required' => true,
'class' => 'form-control captchain',
'placeholder' => 'Captcha',
'autocomplete' => 'off',
'decorators'=>Array(
'ViewHelper',
'Errors',
),
'validators' => array(
array('validator' => 'StringLength', 'options' => array(0, 20))
)
));
Controller AuthController function loginAction()
$captcha = new Zend_Session_Namespace('captcha');
$captcha->captcha = session_id();
if($dataform['vercode'] != $_SESSION["vercode"]){
$msg="Please enter a correct code!";
$this->view->assign('msg', $msg);
return false;
}
I want to use PJax in Yii Grid View, not with the associative filter that comes inside the Grid View, but with the Search Filter that's outside it, so it can filter the results inside.
Here is the source of the index file:
<div class="cars-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Cars', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
'id',
'name',
['attribute' => 'code',
'label' => 'Colour',
'format' => 'raw',
'value' => 'colour',
'contentOptions' => function ($model, $key, $index, $column){
return ['style' => ' text-align: center; width: 100px;color:white;background-color:#'. $model -> code];
},
'headerOptions' => ['style' => 'text-align: center;'],
],
'price',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
Am I supposed to create an active form just for the part I want to filter? Or is there another way?
If You can't simply add the filter to you table like this
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
I suggest you use a proper action and a proper search function called by submit based on a specified active form
for action form eg:
<?php $form = ActiveForm::begin([
'id' => 'search-form',
'method' => 'post',
'action' => ['controller/yourAction']
]); ?>
in the controller
$model = new yourActiveForm();
if ($model->load(Yii::$app->request->post()) ) {
$dataProvider = $searchModel->search( [ 'yuorSearchModel'=> ['your_att1' => $model->yourValue1]]);
}
then your render
Conforming to yii2 doc
Pjax only deals with the content enclosed between its begin() and
end() calls, called the body content of the widget. By default, any
link click or form submission (for those forms with data-pjax
attribute) within the body content will trigger an AJAX request. In
responding to the AJAX request, Pjax will send the updated body
content (based on the AJAX request) to the client which will replace
the old content with the new one. The browser's URL will then be
updated using pushState. The whole process requires no reloading of
the layout or resources (js, css).
You may configure $linkSelector to specify which links should trigger
pjax, and configure $formSelector to specify which form submission may
trigger pjax.
You must add the
<?php Pjax::begin(); ?>
.... your active form
<?php Pjax::end(); ?>
and configure the proper $linkSelect and $formSelector
In your filter view:
<div id="myFilter">
<?php $form = ActiveForm::begin([
'id' => 'myFilterForm',
'method' => 'post',
'action' => [...],
]); ?>
...
</div>
And make sure you render filter between Pjax::begin and Pjax::end
Yet here comes the trick. If your server does not respond within default timeout, Pjax gets ignored and page reloaded, so make sure the timeout is big enough:
<?php Pjax::begin([
'id'=>'myGrid',
'timeout' => 10000, // <------------ THIS !!!!!!!
'formSelector' => '#myFilterForm'
]); ?>
<?= $this->render('myFilter', ['model' => $searchModel]); ?>
<?= GridView::widget([
...
]); ?>
<?php Pjax::end(); ?>
Also in your controller, you might want to "reset" the search model, so only data from the request used are attributes actually used by search:
public function actionSearch()
{
$searchModel = new MySearch();
if ($searchModel->load(Yii::$app->request->post())) {
$searchModel = new MySearch(); // "reset"
$dataProvider = $searchModel->search(Yii::$app->request->post());
} else {
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
}
return $this->render('search', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
Hope this helps. Cheers!
In YII views folder i have test module and admin.php file to manage contents are below and i render form here where i put the code of form and dropdown in it , i want that grid refresh value of status change in dropdown
Suppose i select "Approved" than Grid show the data where status is approved
<?php
Yii::app()->clientScript->registerScript('dropdown', "
$('.dropdown-form form').submit(function(){
$('#testimonial-grid').yiiGridView('update', {
data: $(this).serialize()
});
return false;
});
");
?>
<h1>Manage Testimonials</h1>
<div class="dropdown-form">
<?php $this->renderPartial('_dropdownform',array(
'model'=>$model,
)); ?>
</div><!-- search-form -->
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'testimonial-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'created_by',
'test_name',
'test_email',
'comments',
'created_at',
/*
'status',
'approved_on',
'approved_by',
*/
array(
'class'=>'CButtonColumn',
),
),
)); ?>
Form below is _dropdownform , it contain a form and dropdown from this dropdown i am choosing the value of status
<div class="wide form">
<?php
$form = $this->beginWidget('CActiveForm', array(
'action' => Yii::app()->createUrl($this->route),
'method' => 'get',
));
?>
<div class="row">
<?php
echo CHtml::dropDownList('status', '', array(0 => 'New', 1 => 'Approved', 2 => 'Declined'), array(
'prompt' => 'Select Status',
'ajax' => array(
'type' => 'POST',
'url' => Yii::app()->createUrl('testimonial/loadthedata'),
//or $this->createUrl('loadcities') if '$this' extends CController
'update' => '#testimonial-grid', //or 'success' => 'function(data){...handle the data in the way you want...}',
'data' => array('status' => 'js:this.value'),
)));
?>
</div>
<div class="row buttons">
<?php //echo CHtml::submitButton('Search'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- search-form -->
AND THE CODE IN MY CONTROLLER OR URL GIVEN IN DROPDOWN TO FETCH DATA IS FOLLOWING ACTION BUT I DONT KNOW HOW TO FETCH DATA FROM THIS FUNCTION AND PASS TO GRID VIEW
public function actionloadthedata() {
if (isset($_POST['status'])) {
$status = $_POST['status'];
if($status==0){
$status='New';
}
if($status==1){
$status='Approved';
}
if($status==2){
$status='Declined';
}
Testimonial::model()->findByAttributes(array('status'=>$status));
}
}
You can use CGridView property filterCssClass to link the grid filter, for example
$this->widget('CGridView', array(
'id' => 'my-list',
'filterCssClass' => '#filterFormId .filter',
And there is filter form
<?php $form = $this->beginWidget('CActiveForm', array(
'id' => 'filter-fomr-id',
)); ?>
<div class="filter clearfix">
<?php echo $form->dropDownList($model, 'name', [0=>'all', '1'=>'some else']); ?>
</div>
Replace #filterFormId .filter on jquery selector specific to you form. In other words, set id attribute for filter form, then use "#THISID .row".
In your gridview file, make sure you have this code:
Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
$('.search-form').toggle();
return false;
});
$('.search-form form').submit(function(){
$('#ad-grid').yiiGridView('update', {
data: $(this).serialize()
});
return false;
});
");
then in the CGridView definition:
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'testimonial-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
...
array(
'name'=>'Status',
'filter'=>CHtml::dropDownList('YourModel[status]', $model->status, array(0 => 'New', 1 => 'Approved', 2 => 'Declined'), array('empty' => '--all--') ),
'value'=>'( $data->status == 0) ? "New": ( $data->status == 1) ? "Approved" : "Declined"',
'htmlOptions' => array(
'style' => 'width: 40px; text-align: center;',
),
),
...
array(
'class'=>'CButtonColumn',
),
),
));
// CGridView
In order to save if/else in the 'value' section, you can implement a method in your model that returns the string associated to the integer.
It works great, just with the default Yii admin.php view, which you can edit as much as you need.
Update
Added support for empty status, does not filter query results
Thanks #Alex for your help but i am successful to make filterdropdown for grid , code is following but will you please tell me that i want that grid show only values where status=New , how i can do when page load grid show values where status is New
but first i paste the working code of dropdown filter for grid
Here is my admin.php file
<?php
$this->breadcrumbs = array(
'Testimonials' => array('index'),
'Manage',
);
$this->menu = array(
array('label' => 'List Testimonial', 'url' => array('index')),
array('label' => 'Create Testimonial', 'url' => array('create')),
);
?>
<h1>Manage Testimonials</h1>
<!-----------drop down form------------->
<?php
Yii::app()->clientScript->registerScript('dropdownfilter', "
$('.dropdown-form form #staticid').change(function(){
$.fn.yiiGridView.update('testimonial-grid', {
data: $(this).serialize()
});
return false;
});
");
?>
<div class="dropdown-form">
<?php
$this->renderPartial('_dropdownfilter', array(
'model' => $model,
));
?>
</div><!-- search-form -->
<?php
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'testimonial-grid',
'dataProvider' => $model->search(),
// 'filter' => $model,
'columns' => array(
'id',
'created_by',
'test_name',
'test_email',
'comments',
'created_at',
'status',
array(
'class' => 'CButtonColumn',
),
),
));
?>
Here is my render partial form where i place the static drop dow
<div class="wide form">
<?php
$form = $this->beginWidget('CActiveForm', array(
'action' => Yii::app()->createUrl($this->route),
'method' => 'get',
));
?>
<div class="row">
<?php
echo CHtml::dropDownList('staticid', '', array('0' => 'New', '1' => 'Approved', '2' => 'Declined'), array(
// 'onChange' => 'this.form.submit()',
'ajax' => array(
'type' => 'POST', //request type
)));
?>
</div>
<?php $this->endWidget(); ?>
And Here is code of my adminaction in controller
public function actionAdmin() {
$model = new Testimonial('search');
$model->unsetAttributes(); // clear any default values
if (isset($_GET['staticid'])) {
$getStatus = $_GET['staticid'];
if ($getStatus == 0)
$status = 'New';
if ($getStatus == 1)
$status = 'Approved';
if ($getStatus == 2)
$status = 'Declined';
$model->status = $status;
}
if (isset($_GET['Testimonial']))
$model->attributes = $_GET['Testimonial'];
$this->render('admin', array(
'model' => $model,
));
}
Now i want that when i actionadmin triggered first time it show status=New values
I have two select buttons and want to filter records, when user select any option I have to fire a event and pass the values of buttons to the controller's action. my code is as under
view
<?php echo $this->Form->create('Employee'); ?>
<fieldset>
<div class="pure-control-group">
<?php echo $this->Form->input('designation', array("label" => "Designation",'type' => 'select', 'id'=>'DesignationType','options' => $settings,'empty' => 'select'));?>
<?php echo $this->Form->input('district', array("label" => "District",'type' => 'select', 'id'=>'districtType','options' => $district,'empty' => 'select'));?>
</div>
</fieldset>
<?php echo $this->Form->end();
$this->Js->get('#DesignationType')->event('change',
$this->Js->request(array(
'controller'=>'employees',
'action'=>'getByCategory'
), array(
'update'=>'#success',
'async' => true,
'method' => 'post',
'dataExpression'=>true,
'data'=> $this->Js->serializeForm(array(
'isForm' => true,
'inline' => true
))
))
);
?>
<div id="success"></div>
controller
public function getByCategory(){
$design_id =$this->request->data['Employee']['designation'];
$district_id =$this->request->data['Employee']['district'];
$this->layout = 'ajax';
}
when i click designation then i m able to get the value of designation but not able to get the value of district .And following error occur
Undefined index: district [APP\Controller\EmployeesController.php, line 18]
so, how can i get the value of district;
Try to send the form id in data variable. that is
Try this :
$data = $this->Js->get('#YourFormId')->serializeForm(array('isForm' => true, 'inline' => true));
$this->Js->get('#DesignationType')->event('change',
$this->Js->request(array(
'controller'=>'employees',
'action'=>'getByCategory'
), array(
'update'=>'#success',
'async' => true,
'method' => 'post',
'dataExpression'=>true,
'data'=> $data
))
);
in my project i am using the cgridview inside a modal window. now i am facing the problem that when i select the pagination the page get reloaded. how can i load the grid view with ajax pagination. my ui code id given below...
<div id="pick-category-modal" title="Pick Category" class="popupinfoholder2">
<div style="width:700px; height:auto;">
<?php
$widget = $this->widget('zii.widgets.grid.CGridView', array(
'id' => 'response-grid',
'dataProvider' => $pickdataset->pickSection(),
'cssFile' => Yii::app()->baseUrl . '/media/css/gridview.css',
'summaryText' => '',
'ajaxUpdate'=>true,
'enablePagination' => true,
'template' => '{items}',
'pager' => array(
'class' => 'LinkPager',
'cssFile' => false,
'header' => false,
'firstPageLabel' => 'First',
'prevPageLabel' => 'Previous',
'nextPageLabel' => 'Next',
'lastPageLabel' => 'Last',
),
'columns' => array(
.....................
.....................
),));
?>
<div class="grid-view-footer">
<div class="paginationholder">
<div id="pagination">
<?php $widget->renderPager(); ?>
</div>
</div>
</div>
</div>
</div>
Just testing this myself a moment ago, it appears that the pager kicked out with renderPager() does not work with the AJAX setting. The CGridView JavaScript only binds the AJAX to pagers inside the <div> rendered by the widget (#response-grid here), so it does not find and use your additional pager.
I just use the default pager that the CGridView renders at the bottom, and that works fine.
You could override the CGridView JS to fix this, or list it as an enhancement on the Yii bug tracker: http://code.google.com/p/yii/issues/list