kartik-v / yii2-widget-select2

Enhanced Yii2 wrapper for the Select2 jQuery plugin (sub repo split from yii2-widgets).
http://demos.krajee.com/widget-details/select2
Other
323 stars 145 forks source link

Problem in selecting multiple select value in a text box using Multi Select and ajax loading #191

Closed karmakarpatrick closed 6 years ago

karmakarpatrick commented 7 years ago

Dear Kartik,

First of all thanks for all the helps by your extensions.

I am getting an issue where i am unable to do multi select using ajax loading. Please help what's wrong in the code:

screen shot 2017-01-30 at 2 28 55 pm screen shot 2017-01-30 at 2 29 10 pm screen shot 2017-01-30 at 2 30 17 pm

I want the email id field as to select multiple email id that is queried from the database using Ajax. Please help.

<?= $form->field($model, 'XXX')->widget(Select2::classname(), [ 'initValueText' => 'Ex: abc@abc.com', 'options' => ['placeholder' => '---Select email-id of evaluator',], 'pluginOptions' => [ 'allowClear' => true, 'minimumInputLength' => 3, 'ajax' => [ 'url' => $url, 'dataType' => 'json', 'data' => new JsExpression('function(params) { return {q:params.term}; }') ], 'escapeMarkup' => new JsExpression('function (markup) { return markup; }'), 'templateResult' => new JsExpression('function(thesisForwardedToPersonEmail) { return thesisForwardedToPersonEmail.Email; }'), 'templateSelection' => new JsExpression('function (thesisForwardedToPersonEmail) { return thesisForwardedToPersonEmail.Email; }'), ], ]) ?>

margori commented 7 years ago

Same problem in similar situation.

I patched the control using this code

if (!isset($this->data)) {
     if (!isset($this->value) && !isset($this->initValueText)) {
        $this->data = [];
     } else {
          $key = isset($this->value) ? $this->value : ($multiple ? [] : '');
          $key = empty($key) ? ($multiple ? [] : '') : $this->value;
          $val = isset($this->initValueText) ? $this->initValueText : $key;

         $this->data = $multiple ? array_combine($key, $val) : [$key => $val];
     }
}

I may create a pull request if this code is valid or good enough.

Please, let me know.

karmakarpatrick commented 7 years ago

Yes Margori, You can create a pull request. The code is perfect.

junaid-rahman commented 6 years ago

No need of any changes,

The problem is with initValueText. Instead of passing an array of key value pair just pass an array of values, that will solve th issue

Example: If your making multy select of countries with 'code => 'name' pair then the array of items will be [ 'ind'=>'india', 'qta'=>'qatar', 'cha'=>'chaina', ... ] So for the select2 widget initValueText you just pass the array of selected values. if india and chaina are selected then the array should be ['india','chaina']

margori commented 6 years ago

I think this change is required since in DB keys of the array are stored, not values.