I use Yiiwheels. I want to change a combo box to select 2 widget, but the pertinent assets are not loaded yet. The ugly solution is creating a dummy select2 element in a hidden span, so assets are loaded automatically. but is there any better way to do that, I mean a function to load assets of a widget?
The function you are looking for is the registerClientScript()
function in WhSelect2
widget class in Yiiwheels.
While creating an empty widget is the easiest way to register the script you can alternatively call it directly with something like this
<?php Yii::import('yiiwheels.widgets.select2.WhSelect2');
$w = new WhSelect2();
$w->registerClientScript();
?>
The registerClientScript()
function is called in init()
call during widget creation, the following is operations executed by this function See WhSelect2 on github for the full code
/**
* Registers required client script for bootstrap select2. It is not used through bootstrap->registerPlugin
* in order to attach events if any
*/
public function registerClientScript()
{
/* publish assets dir */
$path = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'assets';
$assetsUrl = $this->getAssetsUrl($path);
/* @var $cs CClientScript */
$cs = Yii::app()->getClientScript();
$cs->registerCssFile($assetsUrl . '/css/select2.css');
$cs->registerScriptFile($assetsUrl . '/js/select2.js');
if ($this->language) {
$cs->registerScriptFile(
$assetsUrl . '/js/locale/select2_locale_' . $this->language . '.js',
CClientScript::POS_END
);
}
/* initialize plugin */
$selector = '#' . TbArray::getValue('id', $this->htmlOptions, $this->getId());
$this->getApi()->registerPlugin('select2', $selector, $this->pluginOptions, CClientScript::POS_READY);
$this->getApi()->registerEvents($selector, $this->events, CClientScript::POS_READY);
}