Home » Php » php – Yii Bootstrap does not work if not preloaded

php – Yii Bootstrap does not work if not preloaded

Posted by: admin July 12, 2020 Leave a comment

Questions:

I have been using Yii Bootstrap in an application for a while. Now, I have a section where the loaded CSS files are causing issues, and I don’t want to load the bootstrap extension in that controller.

In my configuration file, I had bootstrap set to preload:

'preload' => array('log', 'bootstrap')

I have now removed bootstrap from the preload array, and it stops working saying the alias is incorrect:

Alias “bootstrap.widgets.BootNavbar” is invalid. Make sure it points to an existing directory or file.

The alias though has been defined in the components section of the configuration file and works fine when the bootstrap component is preloaded:

'bootstrap' => array(
    'class' => 'ext.bootstrap.components.Bootstrap'
 ),

What can I do to make the bootstrap extension work without preloading it?

How to&Answers:

Just call this:

Yii::app()->getComponent("bootstrap");

'preload' => 'bootstrap' actually trigers this command. If you just call Yii::app()->bootstrap->init() as suggested by Blizz you will end up calling init() twice, which could be harmful.

Answer:

I create the bootstrap extension in module init() method on this way. Preload is not needed.

 if (!Yii::app()->hasComponent('bootstrap')) {
            Yii::setPathOfAlias('bootstrap', realpath(dirname(__FILE__) . '/extensions/bootstrap'));
            Yii::createComponent('bootstrap.components.Bootstrap')->init();
        }

If you would like to manage Bootstrap component under Yii::app() (e.g. hasComponent method) you can change the last row:

Yii::app()->setComponent('bootstrap',Yii::createComponent('bootstrap.components.Bootstrap'));

This solution not need preload, or init(), but you have to set alias to Boostrap folder manually.

Answer:

You can anytime import it:

Yii::import('ext.bootstrap.components.Bootstrap');