GridView Yii2

Обсуждение документации второй версии фреймворка. Переводы Cookbook и авторские рецепты.
Ответить
Аватара пользователя
mat.twg
Сообщения: 222
Зарегистрирован: 2012.02.22, 20:44
Откуда: Санкт-Петербург

GridView Yii2

Сообщение mat.twg »

Всем привет! Ищу рецепты по виджету GridView... Интересует его 'сложная' конфигурация по аналогии с CGridView

Я буду приводить функции на yii 1.x, было бы интересно во что это превратилось в Yii 2.x

Вот старая функция search:

//Модель

Код: Выделить всё

**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria=new CDbCriteria;
                
                $criteria->with = array('attributeType', 'attributesRu', 'attributesImages');
                
                $criteria->compare('attributesRu.short_name', $this->shortName, true);
                $criteria->compare('attributesRu.name', $this->longName, true);
                
                $criteria->compare('attributesImages.src', $this->image);
                
        $criteria->compare('t.id',$this->id);
        $criteria->compare('t.type',$this->type);
        $criteria->compare('t.disabled',$this->disabled);

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,                         
                        'sort'=>array(
                            'attributes'=>array(
                                'shortName'=>array(
                                    'asc'=>'attributesRu.short_name',
                                    'desc'=>'attributesRu.short_name DESC',
                                ),
                                'longName'=>array(
                                    'asc'=>'attributesRu.name',
                                    'desc'=>'attributesRu.name DESC',
                                ),
                                '*',
                            ),
                        ),
                        'pagination' => array(
                                'pageSize' => 15, 
                        ),
        ));
                

    } 
Search вырос в отдельный класс, может это и правильно... как я понял Criteria уже больше нет, а жаль...


//Контроллер

Код: Выделить всё

public function actionIndex()
    {
                
            $model=new Attributes('search');
            $model->unsetAttributes();  // clear any default values


            if(isset($_GET['Attributes']))
                $model->attributes=$_GET['Attributes'];


            $types=AttributesTypes::model()->findAll();


            if (isset($_GET['ajax'])) {
                $this->renderPartial('_grid',array(
                    'model'=>$model,
                    'types'=>$types,
                ));
            }
            else {
                $this->render('index',array(
                    'model'=>$model,
                    'types'=>$types,
                ));
            }   
    } 
Ну с экшенами контроллера вопросов не возникает, привёл для полноты картины

//Вьюха

Код: Выделить всё

$this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'attributes-grid',
    'dataProvider'=>$model->search(),
    'filter'=>$model,
        'itemsCssClass'=>'table table-striped table-bordered', 
        'ajaxUpdate'=>true,
        'htmlOptions'=>array('style'=>'margin:0px'),
        'template'=>'{summary}{items}{pager}',
    
    'columns'=>array(
                array(
                    'type'=>'raw',
                    'name'=>'id',
                    'headerHtmlOptions'=>array('style'=>'width:40px;'),
                    'filterHtmlOptions'=>array('style'=>'height:0px; padding:5px'),
                    'filter'=>CHtml::textField('Attributes[id]', $model->id, array('style'=>'width:40px;margin:0px;')),
                ),
            
                array(
                    'type'=>'html',
                    'name'=>'image',
                    'headerHtmlOptions'=>array('style'=>'width:40px;'),
                    'filterHtmlOptions'=>array('style'=>'height:0px; padding:5px'),
                    'htmlOptions'=>array('style'=>'padding:0px; margin:0px; text-align:center'),
                    'filter'=>false,
                    'value'=>'(!empty($data->attributesImages["src"]))?CHtml::image(Yii::app()->request->hostInfo.Yii::app()->baseUrl."/'.$this->thumbDir.'_".$data->attributesImages["src"],"",array("style"=>"width:31px;height:31px;line-height:normal")):""'
                ),
            
                array(
                    'type'=>'raw',
                    'name'=>'type',
                    'headerHtmlOptions'=>array('style'=>'width:80px;'),
                    'filterHtmlOptions'=>array('style'=>'height:0px; padding:5px'),
                    'filter'=>CHtml::dropDownList('Attributes[type]', $model->type, CHtml::listData($types, 'id', 'name'), array('empty'=>'', 'style'=>'margin:0px;')),
                    'value'=>'$data->attributeType["name"]',

                ),

                array(
                    'type'=>'raw',
                    'name'=>'disabled',
                    'headerHtmlOptions'=>array('style'=>'width:80px;'),
                    'filterHtmlOptions'=>array('style'=>'height:0px; padding:5px'),
                    'filter'=>CHtml::dropDownList('Attributes[disabled]', $model->disabled, array('empty'=>'', 1=>'Выкл.', 0=>'Вкл.'), array('style'=>'width:80px; margin:0px;')),

                ),

                array(
                    'type'=>'raw',
                    'name'=>'shortName',
                    'headerHtmlOptions'=>array('style'=>'width:120px;'),
                    'filterHtmlOptions'=>array('style'=>'height:0px; padding:5px'),
                    'filter'=>CHtml::textField('Attributes[shortName]', $model->shortName, array('style'=>'width:120px;margin:0px;')),
                    'value'=>'$data->attributesRu["short_name"]',

                ),
            
                array(
                    'type'=>'raw',
                    'name'=>'longName',
                    'filterHtmlOptions'=>array('style'=>'height:0px; padding:5px'),
                    'filter'=>CHtml::textField('Attributes[longName]', $model->longName, array('style'=>'width:250px;margin:0px;')),
                    'value'=>'$data->attributesRu["name"]',

                ),
                
                array(
                        'class'=>'CButtonColumn',
                ),
    ),
)); 
А вот тут тьма:

- Вывод в колонку значений типа (disabled) ? Да : Нет
- Фильтрация по моделям со связями, именно по полям заJOINненой таблицы.
- Картинки в ячейках

--

ps:
Дайте, пожалуйста, ссылки на рецепты, если таковы существуют.
Аватара пользователя
vova07
Сообщения: 1004
Зарегистрирован: 2012.11.29, 14:52
Откуда: Chisinau, Moldova

Re: GridView Yii2

Сообщение vova07 »

mat.twg писал(а):- Вывод в колонку значений типа (disabled) ? Да : Нет
https://github.com/yiisoft/yii2/blob/f1 ... r.php#L385
mat.twg писал(а):- Картинки в ячейках
https://github.com/yiisoft/yii2/blob/f1 ... r.php#L352

Пример:

Код: Выделить всё

'columns' => [
    'status_id:boolean',
    // или
    [
        'attribute' => 'image_url',
        'format' => 'image'
    ]
] 
mat.twg писал(а):- Фильтрация по моделям со связями, именно по полям заJOINненой таблицы.
Пример представления: https://github.com/vova07/yii2-start-us ... ex.php#L45
Пример поисковой модели: https://github.com/vova07/yii2-start-us ... ch.php#L59
Пример контроллера: https://github.com/vova07/yii2-start-us ... er.php#L62

Атрибуты name, surname являются JOIN атрибутами, и хранятся в отдельной таблице "profile", основные атрибуты в таблице "user". Суть проста, делается изначально "joinWith()", а дальше стандартный "andFilterWhere". В выводе все просто: простые связаны атрибуты.
Аватара пользователя
ifelse
Сообщения: 227
Зарегистрирован: 2013.02.05, 13:05

Re: GridView Yii2

Сообщение ifelse »

А как в фильтре сделать dropdown-список вместо простого инпута?
Аватара пользователя
vova07
Сообщения: 1004
Зарегистрирован: 2012.11.29, 14:52
Откуда: Chisinau, Moldova

Re: GridView Yii2

Сообщение vova07 »

Аватара пользователя
mat.twg
Сообщения: 222
Зарегистрирован: 2012.02.22, 20:44
Откуда: Санкт-Петербург

Re: GridView Yii2

Сообщение mat.twg »

Василий! Спасибо добрый человек! Проштудирую, бегло глянул, кажется то что искал :)
longmayar
Сообщения: 55
Зарегистрирован: 2014.12.08, 16:11

Re: GridView Yii2

Сообщение longmayar »

vova07 писал(а):
mat.twg писал(а):- Фильтрация по моделям со связями, именно по полям заJOINненой таблицы.
Пример поисковой модели: https://github.com/vova07/yii2-start-us ... ch.php#L59

Суть проста, делается изначально "joinWith()", а дальше стандартный "andFilterWhere"
А если мне не нужно при любых вызовах search делать JOIN - как тогда быть? Писать второй метод search() или переписывать этот, добавляя параметры и логику?
Andrewkha
Сообщения: 132
Зарегистрирован: 2014.11.08, 21:27

Re: GridView Yii2

Сообщение Andrewkha »

https://www.youtube.com/watch?v=Fw6k3BE ... 20VxLx2mkF
вот тут хорошо расскахано/показано
Аватара пользователя
leonidps
Сообщения: 268
Зарегистрирован: 2011.01.18, 19:40
Откуда: Псков

Re: GridView Yii2

Сообщение leonidps »

Использование свойства "footer" для публикации итогов
реализуем класс

Код: Выделить всё

namespace app\components;
class PTotal {
    public static function pageTotal($provider, $fieldName)
    {
        $total=0;
        foreach($provider as $item){
            $total+=$item[$fieldName];
        }
        return $total;
    }
}
 
заполним массив моделей

Код: Выделить всё

$provider = new ActiveDataProvider([
    'query' => $query,
    'sort' => $sort,
]);
 
реализуем массив столбцов, конфигурируем нужные

Код: Выделить всё

$grid_columns=[         
      [
        'label'=>'Услуга',
        'attribute' => 'usluga_alias',
        'value' => function ($model) {
            return Html::a($model['usluga_alias'], ['/admin/saldo/update','id'=>$model['saldo_id']]);
        },
        'format'=>'raw',
        'footer'=>'Итого',
    ],
    [
        'header'=>'Вход.</br>сальдо',
        'attribute' => 'saldo_in',
        'options'=>['style'=>'width:8%;'],
        'footer'=>PTotal::pageTotal($provider->models,'saldo_in'),
    ],
]    
конфигурируем виджет

Код: Выделить всё

echo GridView::widget([
    'dataProvider' => $provider,
    'id' =>'saldo-grid',
    'showFooter'=>TRUE,
    'summaryOptions' => ['class' => 'pull-right'],
    'caption' => 'Сальдо услуг',
    'captionOptions' => ['class'=>'h4 text-center text-info'],
    'footerRowOptions'=>['style'=>'font-weight:bold;text-decoration: underline;'],
    'columns' =>$grid_columns,
]); 
Правила существуют не только для того, чтобы их нарушать.
Ответить