CGridView
$this->widget('zii.widgets.grid.CGridView', array( 'id'=>'types-grid', 'dataProvider'=>$model->search(), 'filter'=>$model, 'columns'=>array( 'id', 'name', //'category', array( 'name'=>'category', 'header' => 'Имя', 'headerHtmlOptions' => array('width' => '20%'), 'htmlOptions' => array('class' => 'my'), // Фильтер шапки в таблице 'filter' => CHtml::dropDownList('ReferenceValues[category_filter]', $currentCategory, $this->getModelItems('Category')), // Вывод значений 'value'=>'CHtml::link(Types::GetCategoryName($data->category), Yii::app()->createUrl("/esreestr/categories/update/id/".$data->category))', 'type' => 'html', ), array( // Установка кнопок 'class'=>'CButtonColumn', ), ), ));
Rows
Вывод значений таблицы
... 'value'=>'CHtml::link(Types::GetCategoryName($data->category), Yii::app()->createUrl("/esreestr/categories/update/id/".$data->category))', 'type' => 'html', ...
Filters
Устанавливает вывод фильтра в загаловке таблицы
... 'filter' => CHtml::dropDownList('ReferenceValues[category_filter]', $currentCategory, $this->getModelItems('Category')), ...
Сортировка
Сортировка с применение класса CSort
$sort = new CSort(); $sort->attributes = array( 'asc' => 'date', 'desc' => 'date DESC', ); $this->widget('zii.widgets.grid.CGridView', array( 'id'=>'types-grid', 'dataProvider'=>$model->search(), 'filter'=>$model, 'sort' => $sort, 'columns'=>array( 'id', 'name', //'category', array( 'name'=>'category', // Фильтер шапки в таблице 'filter' => CHtml::dropDownList('ReferenceValues[category_filter]', $currentCategory, $this->getModelItems('Category')), // Вывод значений 'value'=>'CHtml::link(Types::GetCategoryName($data->category), Yii::app()->createUrl("/esreestr/categories/update/id/".$data->category))', 'type' => 'html', ), array( // Установка кнопок 'class'=>'CButtonColumn', ), ), ));
Страницы
Model
public function search() { $criteria=new CDbCriteria; $criteria->compare('ID',$this->ID); $criteria->compare('REGION',$this->REGION,true); $criteria->compare('TITLE',$this->TITLE,true); $criteria->compare('PHONE',$this->PHONE,true); $criteria->compare('EMAIL',$this->EMAIL,true); return new CActiveDataProvider(get_class($this), array( 'criteria'=>$criteria, 'pagination' => array("pageSize" => 20), )); }
Views
<?php $this->widget('zii.widgets.grid.CGridView', array( 'dataProvider'=>$dataProvider, 'cssFile' => Yii::app()->baseUrl . '/media/css/gridview.css', 'columns'=>array( 'REGION', 'TITLE', 'PHONE', 'EMAIL', ), 'enablePagination' => true, 'pager' => array( 'class' => 'LinkPager', 'cssFile' => false, 'header' => false, 'firstPageLabel' => 'First', 'prevPageLabel' => 'Previous', 'nextPageLabel' => 'Next', 'lastPageLabel' => 'Last', ), ) ); ?>
LinkPager.php
class LinkPager extends CLinkPager { public $maxButtonCount=3; }
CSS
.yiiPager .hidden, .yiiPager .first, .yiiPager .last { display: none; }
Размер страницы
config
// Accessable with Yii::app()->params['paramName'] 'params'=>array ( 'defaultPageSize'=>20,
controller
// page size drop down changed if (isset($_GET['pageSize'])) { Yii::app()->user->setState('pageSize',(int)$_GET['pageSize']); unset($_GET['pageSize']); // would interfere with pager and repetitive page size change }
model
return new CActiveDataProvider(get_class($this),array( 'pagination'=>array( 'pageSize'=> Yii::app()->user->getState('pageSize',Yii::app()->params['defaultPageSize']), ), 'criteria'=>$criteria, ));
views
<?php // put this somewhere on top $pageSize=Yii::app()->user->getState('pageSize',Yii::app()->params['defaultPageSize']); ?> <?php // we use header of button column for the drop down // so change the CButtonColumn in columns array like this: ... array( 'class'=>'CButtonColumn', 'header'=>CHtml::dropDownList('pageSize',$pageSize,array(20=>20,50=>50,100=>100),array( // change 'user-grid' to the actual id of your grid!! 'onchange'=>"$.fn.yiiGridView.update('user-grid',{ data:{pageSize: $(this).val() }})", )), ),
datePicker в CGridView
CJuiDatePicker
'filter'=>$this->widget('zii.widgets.jui.CJuiDatePicker', array( 'model'=>$model, 'attribute'=>'date_created', 'language'=>'ru', 'options'=>array( 'showAnim'=>'fold', 'dateFormat'=>'yy-mm-dd', 'changeMonth' => 'true', 'changeYear'=>'true', 'showButtonPanel' => 'true', ), ),true),
CGridView
<?php $this->widget('zii.widgets.grid.CGridView', array( 'dataProvider'=>$model->search(), 'filter'=>$model, 'afterAjaxUpdate'=>"function() { jQuery('#News_date_created').datepicker( jQuery.extend(jQuery.datepicker.regional['ru'],{ 'showAnim':'fold', 'dateFormat':'yy-mm-dd', 'changeMonth':'true', 'showButtonPanel':'true', 'changeYear':'true' }) ); }", 'columns'=>array( array( 'name'=>'title', 'type'=>'raw', 'value'=>'CHtml::link(CHtml::encode($data->title), $data->url)' ), array( 'name'=>'dateCreated', 'type'=>'raw', 'filter'=>$this->widget('zii.widgets.jui.CJuiDatePicker', array( 'model'=>$model, 'attribute'=>'date_created', 'language'=>'ru', 'options'=>array( 'showAnim'=>'fold', 'dateFormat'=>'yy-mm-dd', 'changeMonth' => 'true', 'changeYear'=>'true', 'showButtonPanel' => 'true', ), ),true), 'htmlOptions' => array('style' => 'width:130px;'), ), array( 'class'=>'CButtonColumn', 'deleteConfirmation' =>'Are you sure you want to delete this news?', 'viewButtonUrl' => '$data->url', ), ), )); ?>
Затем в методе модели search прописываем
if ($this->date_created) $criteria->compare('date_created', $this->date_created, true);
Вывод двух CGridView для разных таблиц
Иногда бывает необходимо отобразить на одной странице в двух CGridView данные из двух моделей
В контроллере напишем следующее:
public function actionAdmin() { Yii::import('application.modules.apartmentCity.models.ApartmentCity'); $modelA = new $this->modelName('search'); $modelB = new ApartmentCity('search'); $this->render('admin', array('modelA' => $modelA, 'modelB' => $modelB)); }
Представление 'admin' принимает следующий вид
<?php $this->widget('zii.widgets.grid.CGridView', array( 'dataProvider'=>$modelA->search(), 'columns'=>array( array( 'name'=>'title', 'type'=>'raw', 'value'=>'CHtml::link(CHtml::encode($data->title), $data->url)' ), array( 'name'=>'dateCreated', 'type'=>'raw', 'filter'=>false, 'htmlOptions' => array('style' => 'width:130px;'), ), array( 'class'=>'CButtonColumn', 'deleteConfirmation' => 'Are you sure you want to delete this news?', 'viewButtonUrl' => '$data->url', ), ), )); ?> <?php $this->widget('zii.widgets.grid.CGridView', array( 'dataProvider'=>$modelB->search(), 'columns'=>array( array( 'name' => 'name', 'header' => 'Название', ), array( 'class'=>'CButtonColumn', 'template'=>'{update} {delete}', 'buttons'=>array( 'delete'=>array( 'label'=>'Delete', 'url'=>'Yii::app()->createUrl("apartmentCity/delete", array("id"=>$data->id))', ), 'update'=>array( 'label'=>'Update', 'url'=>'Yii::app()->createUrl("apartmentCity/update", array("id"=>$data->id))', ), ), ), ), )); ?>
Пример метода search модели News
public function search() { return new CActiveDataProvider($this, array( 'sort' => array( 'defaultOrder' => 'date_created DESC', ), 'pagination' => array( 'pageSize' => param('adminPaginationPageSize', 20), ), )); }
Действие после удаления записи в CGridView
Дано: таблица, вывод записей которой, в привычном нам CGridView.
Задача: не давать пользователю удалять последнюю запись и выводить соответствующие сообщение.
В нашу "таблицу" добавим:
'afterDelete'=>'function(link, success, data){ if (data == 0) {alert("Удалить последний тип нельзя по причине необходимости данного поля в каждом объявлении."); } }',
Получится так
array( 'class'=>'CButtonColumn', 'deleteConfirmation' => 'Вы точно хотите удалить выбранный элемент?', 'afterDelete'=>'function(link, success, data){ if (data == 0) {alert("Удалить последний элемент нельзя!"); } }' )
В метод beforeDelete модели
public function beforeDelete(){ if($this->model()->count() <= 1){ echo 0; return false; } }
Обновление грида через ajax
Enable In-place Editing in Yii Grid
Ajax button in CGridView
'columns' => array( 'id', 'name', array( 'class'=>'CButtonColumn', 'template' => '{view} {update} {delete}', 'buttons'=>array( 'view' => array( 'url'=>'"index.php?r=admin/view&id=".$data->user_id."&m=users"', 'click' => "function (){ $('#viewTab').load($(this).attr('href'));return false; }" ) ), ), )
CStarRating
views
$this->grid->controller->widget("CStarRating", array("name" => $data->id, "id" => $data->id, "value" => $data->rating, "readOnly" => true,),true);
GridView
$this->widget('bootstrap.widgets.TbGridView', array( 'id'=>'users-comments-grid', 'dataProvider'=>$model->search(), 'filter'=>$model, 'afterAjaxUpdate'=>"function() { jQuery('.rating-block input').rating({'readOnly':true}); }", 'columns'=>array( array( 'name' => 'message', 'sortable' => false, ), array( 'name' => 'rating', 'type' => 'raw', 'value'=>'$this->grid->controller->widget("CStarRating", array("name" => $data->id, "id" => $data->id, "value" => $data->rating, "readOnly" => true,),true)', 'headerHtmlOptions' => array('style' => 'width:85px;'), 'htmlOptions' => array('class' => 'rating-block'), 'filter' => false, 'sortable' => false, ), ), ));