How do I set a default configuration for GridView in Yii2 without the widget factory?

删除回忆录丶 提交于 2019-12-21 07:23:53

问题


This is what a gridview looks like in Yii2:

<?php echo GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        ...
        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>

I want change my grids a little bit, so I add this line:

tableOptions'=>['class'=>'table table-condensed'], 

This works great, but...

I want this to be the default value for all my grids!

In Yii 1, this would look like this:

'widgetFactory' => array(
    'widgets' => array(
        'CGridView' => array(
            'htmlOptions' => ['class'=>'table table-condensed']
        ),
    ),
),

In Yii2 however there is no widget factory. Instead, looking at the main config, I would expect this to work:

'grid'=>[
    'class' => 'yii\grid\GridView',
    'tableOptions'=>['class'=>'table table-condensed'],
],

But it does not. So what am I doing wrong? Any hints much appreciated. Thanks!


回答1:


You can use Yii::$container->set().

For example:

// add following line in config/web.php and config/console.php
require __DIR__ . '/container.php';

// creates a config/container.php file and add following
\Yii::$container->set('yii\grid\GridView', [
    'tableOptions' => [
        'class' => 'table table-condensed',
    ],
]);

For more information: Dependency Injection Container and Practical Usage

and Yii::$objectConfig has been removed in Yii 2.0.0-beta.

For example (Since version 2.0.11):

$config = [
    'id' => 'basic',
    // ...
    'container' => [
        'definitions' => [
            yii\grid\GridView::class => [
                'tableOptions' => [
                    'class' => 'table table-condensed',
                ],
            ],
        ],
    ],
];

For more information: Application Configurations




回答2:


Edit: This answer is no longer applicable since Yii 2.0.0-beta.

Yii::$objectConfig = [
    'yii\grid\GridView' => [
        'tableOptions'=>['class'=>'table table-condensed']
    ],
];


来源:https://stackoverflow.com/questions/20183622/how-do-i-set-a-default-configuration-for-gridview-in-yii2-without-the-widget-fac

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!