Skip to content

Commit

Permalink
Update to release v2.0.5
Browse files Browse the repository at this point in the history
  • Loading branch information
kartik-v committed Dec 21, 2015
1 parent ffc59ce commit b457bce
Show file tree
Hide file tree
Showing 36 changed files with 860 additions and 101 deletions.
20 changes: 17 additions & 3 deletions CHANGE.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,27 @@
Change Log: `yii2-widget-select2`
=================================

## Version 2.0.5

**Date:** 21-Dec-2015

- (enh #69): Add ability to select and unselect all options for multiple select.
- (enh #97): Allow maintaining order of pills selected for multiple select.
- (enh #98): Various enhancements to the Select2 widget.
- Fix the plugin bug which does not close the dropdown when a value is cleared using the `x` clear indicator.
- Enhance widget to show bootstrap `success` and `error` states for active field trapped errors
- Better and more dynamic theming support
- Allow select2 to be reset correctly when parent form is reset (controlled by boolean property `changeOnReset`)
- (ref enh #69): Enable SELECT ALL and UNSELECT ALL to toggle all options for multiple select (new property `toggleAllSettings`). Allow complete configuration and styling of the same .
- (ref enh #97): Enable select2 dropdown to maintain the right order of tags/options for multiple select (new boolean property `maintainOrder` which defaults to `false`. Set this to `true` to maintain order)
- Consolidate and refactor code to just call one additional JS initialization script after plugin initialization. A new data-attribute `data-s2-options` is now stored in parent select input. This will store the global variable that will maintain the additional Json encoded options to be used by `initS2Loading` method.
- (enh #99): Add messages and translations support.

## Version 2.0.4

**Date:** 14-Dec-2015
**Date:** 22-Sep-2015

- (enh #67): Remove redundant code in embedAddon.
- (enh #94): Update to latest release of Select2 plugin.
- (enh #96): Enhance fix for clearing Select2 selection.

## Version 2.0.3

Expand Down
190 changes: 138 additions & 52 deletions Select2.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* @copyright Copyright © Kartik Visweswaran, Krajee.com, 2014 - 2015
* @package yii2-widgets
* @subpackage yii2-widget-select2
* @version 2.0.4
* @version 2.0.5
*/

namespace kartik\select2;
Expand All @@ -14,7 +14,9 @@
use Yii;
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;
use yii\web\JsExpression;
use yii\web\View;

/**
* Select2 widget is a Yii2 wrapper for the Select2 jQuery plugin. This input widget is a jQuery based replacement for
Expand All @@ -37,36 +39,34 @@ class Select2 extends InputWidget
const THEME_KRAJEE = 'krajee';

/**
* @var array $data the option data items. The array keys are option values, and the array values
* are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
* For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
* If you have a list of data models, you may convert them into the format described above using
* [[\yii\helpers\ArrayHelper::map()]].
* @var array $data the option data items. The array keys are option values, and the array values are the
* corresponding option labels. The array can also be nested (i.e. some array values are arrays too). For each
* sub-array, an option group will be generated whose label is the key associated with the sub-array. If you
* have a list of data models, you may convert them into the format described above using
* [[\yii\helpers\ArrayHelper::map()]].
*/
public $data;

/**
* @var string the locale ID (e.g. 'fr', 'de') for the language to be used by the Select2 Widget.
* If this property not set, then the current application language will be used.
* @var string the locale ID (e.g. 'fr', 'de') for the language to be used by the Select2 Widget. If this property
* not set, then the current application language will be used.
*/
public $language;

/**
* @var string the theme name to be used for styling the Select2
* @var string the theme name to be used for styling the Select2.
*/
public $theme = self::THEME_KRAJEE;

/**
* @var bool whether to trigger change for Select2 input on form reset
* so the Select2 value is rightly reset.
* @var bool whether to trigger change for Select2 input on form reset so the Select2 value is rightly reset.
*/
public $changeOnReset = true;

/**
* @var string|array, the displayed text in the dropdown for the initial
* value when you do not set or provide `data` (e.g. using with ajax).
* If options['multiple'] is set to `true`, you can set this as an array of
* text descriptions for each item in the dropdown `value`.
* @var string|array, the displayed text in the dropdown for the initial value when you do not set or provide
* `data` (e.g. using with ajax). If options['multiple'] is set to `true`, you can set this as an array of text
* descriptions for each item in the dropdown `value`.
*/
public $initValueText;

Expand All @@ -75,33 +75,74 @@ class Select2 extends InputWidget
*/
public $hideSearch = false;

/**
* @var bool whether to show the toggle all button for selection all options in a multiple select.
*/
public $showToggleAll = true;

/**
* @var bool whether to maintain the order of tag / option selected for a multiple select
*/
public $maintainOrder = false;

/**
* @var array the toggle all button settings for selecting/unselecting all the options. This is applicable only for
* multiple select. The following array key properties can be set:
* - `selectLabel`: string, the markup to be shown to select all records. Defaults to `<i class="glyphicon
* glyphicon-unchecked"></i> Select all`.
* - `unselectLabel`: string, the markup to be shown to unselect all records. Defaults to `<i class="glyphicon
* glyphicon-checked"></i> Unselect all`.
* - `selectOptions`: array, the HTML attributes for the container wrapping the select label. Defaults to `[]`.
* - `unselectOptions`: array, the HTML attributes for the container wrapping the unselect label. Defaults to `[]`.
* - `options`: array, the HTML attributes for the toggle button container. Defaults to:
* `['class' => 's2-togall-button']`.
*/
public $toggleAllSettings = [];

/**
* @var array addon to prepend or append to the Select2 widget
* - prepend: array the prepend addon configuration
* - content: string the prepend addon content
* - asButton: boolean whether the addon is a button or button group. Defaults to false.
* - append: array the append addon configuration
* - content: string the append addon content
* - asButton: boolean whether the addon is a button or button group. Defaults to false.
* - groupOptions: array HTML options for the input group
* - contentBefore: string content placed before addon
* - contentAfter: string content placed after addon
* - prepend: array|string the prepend addon configuration. If set as a string will be rendered as is. If set as an
* array, the following properties can be set:
* - content: string, the prepend addon content
* - asButton: bool, whether the addon is a button or button group. Defaults to false.
* - append: array|string the append addon configuration. If set as a string will be rendered as is. If set as an
* array, the following properties can be set:
* - content: string, the append addon content
* - asButton: bool, whether the addon is a button or button group. Defaults to false.
* - groupOptions: array, HTML options for the input group
* - contentBefore: string, content placed before addon
* - contentAfter: string, content placed after addon
*/
public $addon = [];

/**
* @var string Size of the Select2 input, must be one of the
* [[LARGE]], [[MEDIUM]] or [[SMALL]]. Defaults to [[MEDIUM]]
* @var string Size of the Select2 input, must be one of the `Select2::LARGE`, `Select2::MEDIUM` or
* `Select2::SMALL`. Defaults to `Select2::MEDIUM`.
*/
public $size = self::MEDIUM;

/**
* @var array the HTML attributes for the input tag. The following options are important:
* - multiple: boolean whether multiple or single item should be selected. Defaults to false.
* - placeholder: string placeholder for the select item.
* - multiple: bool, whether multiple or single item should be selected. Defaults to false.
* - placeholder: string, placeholder for the select item.
*/
public $options = [];

/**
* @var string the variable that will store additional options for Select2 to add enhanced features after the
* plugin is loaded and initialized. This variable name will be stored as a data attribute `data-s2-options`
* within the base select input options.
*/
protected $_s2OptionsVar;

/**
* @inheritdoc
*/
protected $_msgCat = 'kvselect';

/**
* @var array list of inbuilt themes
*/
protected static $_inbuiltThemes = [
self::THEME_DEFAULT,
self::THEME_CLASSIC,
Expand All @@ -112,17 +153,26 @@ class Select2 extends InputWidget
/**
* @inheritdoc
*/
public function init()
public function run()
{
parent::run();
$this->renderWidget();
}

/**
* Initializes and renders the widget
*/
public function renderWidget()
{
parent::init();
$this->initI18N(__DIR__);
$this->pluginOptions['theme'] = $this->theme;
if (!empty($this->addon) || empty($this->pluginOptions['width'])) {
$this->pluginOptions['width'] = '100%';
}
$multiple = ArrayHelper::getValue($this->pluginOptions, 'multiple', false);
unset($this->pluginOptions['multiple']);
$multiple = ArrayHelper::getValue($this->options, 'multiple', $multiple);
$this->options['multiple'] = $multiple;
if (!empty($this->addon) || empty($this->pluginOptions['width'])) {
$this->pluginOptions['width'] = '100%';
}
if ($this->hideSearch) {
$this->pluginOptions['minimumResultsForSearch'] = new JsExpression('Infinity');
}
Expand All @@ -138,10 +188,40 @@ public function init()
}
Html::addCssClass($this->options, 'form-control');
$this->initLanguage('language', true);
$this->renderToggleAll();
$this->registerAssets();
$this->renderInput();
}

/**
* Initializes and render the toggle all button
*/
protected function renderToggleAll()
{
if (!$this->options['multiple'] || !$this->showToggleAll) {
return;
}
$settings = array_replace_recursive([
'selectLabel' => '<i class="glyphicon glyphicon-unchecked"></i>' . Yii::t('kvselect', 'Select all'),
'unselectLabel' => '<i class="glyphicon glyphicon-check"></i>' . Yii::t('kvselect', 'Unselect all'),
'selectOptions' => [],
'unselectOptions' => [],
'options' => ['class' => 's2-togall-button']
], $this->toggleAllSettings);
$sOptions = $settings['selectOptions'];
$uOptions = $settings['unselectOptions'];
$options = $settings['options'];
$prefix = 's2-togall-';
Html::addCssClass($options, "{$prefix}select");
Html::addCssClass($sOptions, "s2-select-label");
Html::addCssClass($uOptions, "s2-unselect-label");
$options['id'] = $prefix . $this->options['id'];
$labels = Html::tag('span', $settings['selectLabel'], $sOptions) .
Html::tag('span', $settings['unselectLabel'], $uOptions);
$out = Html::tag('span', $labels, $options);
echo Html::tag('span', $out, ['id' => 'parent-' . $options['id'], 'style' => 'display:none']);
}

/**
* Initializes the placeholder for Select2
*/
Expand Down Expand Up @@ -210,10 +290,8 @@ protected function embedAddon($input)
}

/**
* Renders the source Input for the Select2 plugin.
* Graceful fallback to a normal HTML select dropdown
* or text input - in case JQuery is not supported by
* the browser
* Renders the source Input for the Select2 plugin. Graceful fallback to a normal HTML select dropdown or text
* input - in case JQuery is not supported by the browser
*/
protected function renderInput()
{
Expand All @@ -233,6 +311,7 @@ public function registerAssetBundle()
$view = $this->getView();
$lang = isset($this->language) ? $this->language : '';
Select2Asset::register($view)->addLanguage($lang, '', 'js/i18n');
Select2AddlAsset::register($view);
if (in_array($this->theme, self::$_inbuiltThemes)) {
/**
* @var AssetBundle $bundleClass
Expand All @@ -242,27 +321,34 @@ public function registerAssetBundle()
}
}

/**
* Parses the variable for boolean value and returns a right JS expression
*
* @return JsExpression
*/
protected static function parseBool($var)
{
return new JsExpression($var ? 'true' : 'false');
}

/**
* Registers the needed assets
*/
public function registerAssets()
{
$id = $this->options['id'];
$this->registerAssetBundle();
// do not open dropdown when clear icon is pressed to clear value
$js = "\$('#{$id}').on('select2:open', initS2Open).on('select2:unselecting', initS2Unselect);";
$this->getView()->registerJs($js);
$size = empty($this->addon) && $this->size !== self::MEDIUM ? 'input-' . $this->size : '';
// register plugin
if ($this->pluginLoading) {
$reset = $this->changeOnReset ? 'true' : 'false';
$this->registerPlugin(
'select2',
"jQuery('#{$id}')",
"initS2Loading('{$id}', '.select2-container--{$this->theme}', '{$size}', {$reset})"
);
} else {
$this->registerPlugin('select2');
}
$isMultiple = $this->options['multiple'];
$options = Json::encode([
'themeCss' => ".select2-container--{$this->theme}",
'sizeCss' => empty($this->addon) && $this->size !== self::MEDIUM ? 'input-' . $this->size : '',
'doReset' => static::parseBool($this->changeOnReset),
'doToggle' => static::parseBool($isMultiple && $this->showToggleAll),
'doOrder' => static::parseBool($isMultiple && $this->maintainOrder)
]);
$this->_s2OptionsVar = 's2options_' . hash('crc32', $options);
$this->options['data-s2-options'] = $this->_s2OptionsVar;
$this->getView()->registerJs("var {$this->_s2OptionsVar} = {$options};", View::POS_HEAD);
$this->registerPlugin('select2', "jQuery('#{$id}')", "initS2Loading('{$id}','{$this->_s2OptionsVar}')");
}
}
31 changes: 31 additions & 0 deletions Select2AddlAsset.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

/**
* @copyright Copyright &copy; Kartik Visweswaran, Krajee.com, 2014 - 2015
* @package yii2-widgets
* @subpackage yii2-widget-select2
* @version 2.0.5
*/

namespace kartik\select2;

use kartik\base\AssetBundle;

/**
* Asset bundle for Select2 Additional CSS
*
* @author Kartik Visweswaran <[email protected]>
* @since 1.0
*/
class Select2AddlAsset extends AssetBundle
{
/**
* @inheritdoc
*/
public function init()
{
$this->setSourcePath(__DIR__ . '/assets');
$this->setupAssets('css', ['css/select2-addl']);
parent::init();
}
}
8 changes: 4 additions & 4 deletions Select2Asset.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,20 @@
* @copyright Copyright &copy; Kartik Visweswaran, Krajee.com, 2014 - 2015
* @package yii2-widgets
* @subpackage yii2-widget-select2
* @version 2.0.4
* @version 2.0.5
*/

namespace kartik\select2;

use Yii;
use kartik\base\AssetBundle;

/**
* Asset bundle for Select2 Widget
*
* @author Kartik Visweswaran <[email protected]>
* @since 1.0
*/
class Select2Asset extends \kartik\base\AssetBundle
class Select2Asset extends AssetBundle
{
/**
* @inheritdoc
Expand All @@ -29,4 +29,4 @@ public function init()
$this->setupAssets('js', ['js/select2.full', 'js/select2-krajee']);
parent::init();
}
}
}
Loading

0 comments on commit b457bce

Please sign in to comment.