Override Yii2 assetManager config in controller

2019-07-04 08:46发布

I use yii-jui to add some UI elements in the views such as datePicker. In the frontend\config\main-local.php I set the following to change the theme used by the JqueryUI:

$config = [
    'components' => [
        'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => 'gjhgjhghjg87hjh8878878',
        ],
        'assetManager' => [
            'bundles' => [
                'yii\jui\JuiAsset' => [
                    'css' =>                    
                      ['themes/flick/jquery-ui.css'],
                ],
            ],
        ],
    ],
];

I tried the following to override this configuration item in the controller actions method:

public function actions() {  

      Yii::$app->components['assetManager'] = [
            'bundles' => [
                'yii\jui\JuiAsset' => [
                    'css' =>                    
                      ['themes/dot-luv/jquery-ui.css'],
                ],
            ],
        ];
      return parent::actions();
    }

Also I tried to set the value of Yii::$app->components['assetManager'] shown above to the view itself (it is partial view of form _form.php) and to the action that calls this view (updateAction). However, all this trying doesn't be succeeded to change the theme. Is there in Yii2 a method like that found in CakePHP such as Configure::write($key, $value);?

2条回答
姐就是有狂的资本
2楼-- · 2019-07-04 09:22

You should modify Yii::$app->assetManager->bundles (Yii::$app->assetManager is an object, not an array), e.g.

Yii::$app->assetManager->bundles = [
    'yii\jui\JuiAsset' => [
        'css' => ['themes/dot-luv/jquery-ui.css'],
    ],
];

Or if you want to keep other bundles config :

Yii::$app->assetManager->bundles['yii\jui\JuiAsset'] = [
    'css' => ['themes/dot-luv/jquery-ui.css'],
];
查看更多
Anthone
3楼-- · 2019-07-04 09:35

You are going about this all wrong, you want to change the JUI theme for 1 controller alone because of a few controls. You are applying 2 css files to different parts of the website that have the potential to change styles in the layouts too. The solution you found works but it is incredibly bad practice.

If you want to change just some controls do it the proper way by using JUI scopes. Here are some links that will help you:
http://www.filamentgroup.com/lab/using-multiple-jquery-ui-themes-on-a-single-page.html
http://jqueryui.com/download/

In this way you are making the website easier to maintain and you do not create a bigger problem for the future than you what solve.

查看更多
登录 后发表回答