I have made a simple widget in my current project of yii2. Simply, it creates a select options list for all jui themes and allow the user to change the theme and save it by the mean of cookies.
This widget need two javascript files, -they are registered in run()- one of them is the jquery cookies plugin. I ask about the being of way to save integrity of this widget and its js files to make it easy to be reused in other Yii2 projects without the need for, maunally, copying all the needed js files?
<?php
namespace common\libs;
use yii;
use yii\base\Widget;
use yii\web\View;
use yii\web\JqueryAsset;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of JuiThemeSelectWidget
*
* @author Said Bakr
*/
class JuiThemeSelectWidget extends Widget
{
private $list;
private $script;
private static $juiThemeSelectId = 'JuiThemesList';
public $themeListId;
public $label;
public function init() {
parent::init();
if ($this->themeListId) self::$juiThemeSelectId = $this->themeListId;
$this->list = $this->createSelectList($this->getThemesList());
$this->makeScript();
}
public static function getThemesList()
{
$themesPath = dirname(Yii::$app->basePath).DIRECTORY_SEPARATOR."vendor".DIRECTORY_SEPARATOR."bower".DIRECTORY_SEPARATOR."jquery-ui".DIRECTORY_SEPARATOR."themes";
$output = [];
foreach (scandir($themesPath) as $item){
if (is_dir($themesPath.DIRECTORY_SEPARATOR.$item) && ($item != '.' && $item !='..')) $output[] = $item;
}
return $output;
}
public static function createSelectList($items)
{
$juiThemeSelectId = self::$juiThemeSelectId;
$output = '';
$output .= "<select id=\"$juiThemeSelectId\">"."
";
foreach ($items as $item){
$output .= "<option value='$item'>$item</option>
";
}
$output .= "</select>
";
return $output;
}
/**
* Making the client-side script for the list */
private function makeScript()
{
$t = self::$juiThemeSelectId;
$this->script = <<<EOD
<script>
var juiThemeSelectId = "$t"
</script>
EOD;
}
public function run() {
parent::run();
$this->getView()->registerJsFile('/myjs/jquery.cookie.js', ['depends' => [JqueryAsset::className()]]);
$this->getView()->registerJsFile('/myjs/JuiThemeSelect.js', ['depends' => [JqueryAsset::className()]]);
return "$this->label $this->list
$this->script";
}
}