diff --git a/composer.json b/composer.json index 811b624..c1e28df 100644 --- a/composer.json +++ b/composer.json @@ -11,6 +11,7 @@ "require": { "php": ">=8.1", "npm-asset/select2": "^4.0.13", + "npm-asset/select2-bootstrap-5-theme": "^1.3.0", "yii2-extensions/asset-bootstrap5": "^0.1", "yiisoft/yii2": "^2.0.49 || ^2.2" }, diff --git a/src/Select2.php b/src/Select2.php index 57dfc1b..20a57a7 100644 --- a/src/Select2.php +++ b/src/Select2.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Yii2\Extension\Select2; +namespace Yii2\Extensions\Select2; use yii\helpers\Html; use yii\helpers\Json; @@ -39,7 +39,20 @@ protected function registerPlugin($name) Select2Asset::register($view); $id = $this->options['id']; if ($this->clientOptions !== false) { - $options = empty($this->clientOptions) ? '' : Json::encode($this->clientOptions); + $options = empty($this->clientOptions) ? [] : $this->clientOptions; + + if (!isset($options['theme'])) { + //Do we have BS5? + if (class_exists('Yii2\Asset\BootstrapAsset')) { + $view->registerCssFile('@npm/select2-bootstrap-5-theme/dist/select2-bootstrap-5-theme.min.css'); + $options['theme'] = 'bootstrap-5'; + } else { + $options['theme'] = 'classic'; + } + } + + $options = Json::encode($options); + $js = "jQuery('#$id').$name($options);"; $view->registerJs($js); } diff --git a/src/Select2Asset.php b/src/Select2Asset.php index c04b851..ffbd48d 100644 --- a/src/Select2Asset.php +++ b/src/Select2Asset.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Yii2\Extension\Select2; +namespace Yii2\Extensions\Select2; use yii\web\AssetBundle; @@ -21,9 +21,24 @@ class Select2Asset extends AssetBundle public $depends = [ 'yii\web\JqueryAsset', - 'yii\bootstrap\BootstrapAsset', ]; + public function init() + { + parent::init(); + + //which BS version is installed (from highest to lowest) + if (class_exists('yii\bootstrap5\BootstrapAsset')) { //BS5 official + $this->depends[] = 'yii\bootstrap5\BootstrapAsset'; + } else if (class_exists('Yii2\Asset\BootstrapAsset')) { //BS5 Yii2-Ext + $this->depends[] = 'Yii2\Asset\BootstrapAsset'; + } else if (class_exists('yii\bootstrap4\BootstrapAsset')) { + $this->depends[] = 'yii\bootstrap4\BootstrapAsset'; + } else { + $this->depends[] = 'yii\bootstrap\BootstrapAsset'; + } + } + /** * @inheritdoc */