|
1 | 1 | <?php |
2 | 2 |
|
3 | 3 | /** |
4 | | - * @copyright Copyright © Kartik Visweswaran, Krajee.com, 2014 - 2019 |
| 4 | + * @copyright Copyright © Kartik Visweswaran, Krajee.com, 2014 - 2020 |
5 | 5 | * @package yii2-widgets |
6 | 6 | * @subpackage yii2-widget-select2 |
7 | | - * @version 2.1.7 |
| 7 | + * @version 2.1.8 |
8 | 8 | */ |
9 | 9 |
|
10 | 10 | namespace kartik\select2; |
@@ -236,7 +236,11 @@ public function renderWidget() |
236 | 236 | if (empty($this->data)) { |
237 | 237 | $emptyValue = !isset($this->value) || $this->value === ''; |
238 | 238 | $emptyInitText = !isset($this->initValueText) || $this->initValueText === ''; |
239 | | - $emptyData = !isset($this->pluginOptions['placeholder']) && !$multiple ? ['' => '']: []; |
| 239 | + if (!isset($this->pluginOptions['placeholder']) && !$multiple && $this->isRequired()) { |
| 240 | + $emptyData = ['' => '']; |
| 241 | + } else { |
| 242 | + $emptyData = []; |
| 243 | + } |
240 | 244 | if ($emptyValue && $emptyInitText) { |
241 | 245 | $this->data = $emptyData; |
242 | 246 | } else { |
@@ -435,4 +439,21 @@ public function registerAssets() |
435 | 439 | } |
436 | 440 | $this->registerPlugin($this->pluginName, "jQuery('#{$id}')", "initS2Loading('{$id}','{$this->_s2OptionsVar}')"); |
437 | 441 | } |
| 442 | + |
| 443 | + protected function isRequired() |
| 444 | + { |
| 445 | + if (!empty($this->options['required'])) { |
| 446 | + return true; |
| 447 | + } |
| 448 | + if (!$this->hasModel()) { |
| 449 | + return false; |
| 450 | + } |
| 451 | + $validators = $this->model->getValidators($this->attribute); |
| 452 | + foreach ($validators as $validator) { |
| 453 | + if ($validator instanceof yii\validators\RequiredValidator) { |
| 454 | + return true; |
| 455 | + } |
| 456 | + } |
| 457 | + return false; |
| 458 | + } |
438 | 459 | } |
0 commit comments