Override Yii2 assetManager config in controller

时光总嘲笑我的痴心妄想 提交于 2019-12-01 22:55:55

问题


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);?


回答1:


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'],
];



回答2:


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.



来源:https://stackoverflow.com/questions/28110404/override-yii2-assetmanager-config-in-controller

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