-2

i'm trying to use the Kartik Select2 Widget for my Yii2 project. I'll use the Ajax Loading and everithing works find, but if i set the multiple option it gives me this error.

PHP Warning – yii\base\ErrorException array_combine(): Both parameters should have an equal number of elements

This error is in Select2.php on this line

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

i think it's because the data attribute is missing, but if i add data attribute ajax doesn't work properly.

This is my view:

$form->field($model, 'lista_art')->widget(Select2::classname(), [
    'initValueText' => "", // set the initial display text
    //'data' => '',
    'options' => ['placeholder' => 'Select a color ...',
                  //'multiple' =>true, // error here
                 ],
    'pluginOptions' => [
        'tags' => true,
        'tokenSeparators' => [',', ' '],
        'allowClear' => true,
        'minimumInputLength' => 3,
        'language' => [
            'errorLoading' => new JsExpression("function () { return 'Waiting for results...'; }"),
        ],
        'ajax' => [
            'url' => \yii\helpers\Url::to(['lista-articoli']),
            'dataType' => 'json',
            'data' => new JsExpression('function(params) { return {q:params.term}; }')
        ],
        'escapeMarkup' => new JsExpression('function (markup) { console.log(markup);return markup; }'),
        'templateResult' => new JsExpression('function(lista_art) { return lista_art.art_modello; }'),
        'templateSelection' => new JsExpression('function (lista_art) { return lista_art.art_modello; }'),
    ],
]);

Also tried to insert multiple option inside 'pluginOptions' array but doesnt work. Is it possible to use multiple option with Ajax Loading?

P.s. I've check my developer toolbar and the response is correct, and gives me what i've expected.

Sfili_81
  • 2,377
  • 8
  • 27
  • 36

1 Answers1

2

You forgot to set data attribute

Sample how to use kartik select 2 with model and active form

$model->keywords = [1, 2];  // NOTE THIS IS AN ARRAY of keys
$form->field($model, 'keywords')->widget(Select2::className(), [
    'pluginOptions' => [
        'tags' => true,
       'multiple' =>true, 
    ],
     'data' => [1=>'keyword1', 2=>'keyword2', 3=>'keyword3'],  
])

Update Try to set up data as empty array like 'data' => []

Marat Badykov
  • 824
  • 4
  • 8
  • wtf! i'll set data like a string and not like an array, i've made a stupid error!! Thank you so much. – Sfili_81 Sep 13 '18 at 09:42