i've some troubles with Select2 kartik plugin for yii2. I set up my plugin with Ajax Loading and, in my create view works fine, so i can select multiple value and save it on database.
When i show the update view i want to set visible the value that i've saved in my database but it show me only a gray rectangle with x icon.
This is what i've tried.
echo $form->field($model, 'lista_art')->widget(Select2::classname(), [
'initValueText' => $art_list,// array of text to show in the tag for the selected items
'showToggleAll' => false,
'options' => ['placeholder' => 'Select...',
'multiple' =>true,
'value' => $value, // array of Id of the selected items
],
'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; }'),
],
]);
And this is the result.
$art_list and $value are array's like this
$art_list = ['name1','name2'];
$value= ['id_name1','id_name2'];
If i inspect the code with browser inspector i find this
<li class="select2-selection__choice" title="name1">
<span class="select2-selection__choice__remove" role="presentation">×</span>
</li>
UPDATE I'll find the error, and it is very trivial.. The error is here
'templateResult' => new JsExpression('function(lista_art) { return lista_art.art_modello; }'),
'templateSelection' => new JsExpression('function (lista_art) { return lista_art.art_modello; }')
There is no lista_art.art_modello because the object for this element is inthe format id:id_name1 and text:name1 so changing the code like this it will work
'templateResult' => new JsExpression('function(lista_art) { return lista_art.text; }'),
'templateSelection' => new JsExpression('function (lista_art) { return lista_art.text; }')