Search code examples
jsonyii2jquery-select2-4kartik-v

Yii2: Kartik's DetailView and Select2 loading id's not text


So I'm loading Kartik's Select2 widget in Kartik's DetailView using multiple input:

[
  'attribute' => 'characters',
  'format'    => 'raw',
  'type'      => DetailView::INPUT_SELECT2,
  'value'     => function($form, $widget) {
                  <my_stuff_in_VIEW_mode>
                 },
  'widgetOptions' => [
            'options'       => ['multiple' => true, 'placeholder' => Yii::t('app', 'Select...')],
            'pluginOptions' => [
               'allowClear'         => true,
               'minimumInputLength' => 3,
               'maximumInputLength' => 20,
               'language'           => Yii::$app->language,
               'ajax' => [
                    'url'      => \yii\helpers\Url::to(['myAjaxServer']),
                    'dataType' => 'json',
                    'delay'    => 250,
                    'data'     => new JsExpression('function(params) { return {q:params.term, p:params.page}; }'),
                    'cache'          => true,
                ],
               'escapeMarkup' => new JsExpression("function (markup) { return markup; }"),
               'templateResult'     => new JsExpression("function (characters) { return '<b>' + characters.text + '</b>'; }"),
               'templateSelection'  => new JsExpression("function (characters) { return characters.text; }"),
            ],
  ],
],

When it comes to Kartik's DetailView, VIEW mode correctly shows my list of characters given by value, but when entering EDIT mode I got this:

enter image description here

which obviously is not what I expected: I want my characters' names rather than their IDs. However if I select new characters from this very same input dropdown, new tags are added which properly show the new names (thus this issue happens when updating data). After I confirm the new data and then try to update, new characters are shown with their IDs again.

JSON data is as follows:

{"results":[{"id":"8","text":"Character8"},{"id":"5","text":"Character5"}],"pagination":{"more":true}}

Any ideas?

UPDATED WITH SOLUTION BY KARTIK BELOW:

Add initValueText as an array of desired attribute values:

'initValueText' => ArrayHelper::getColumn($model->characters, 'name'),

Solution

  • You need to set Select2::initValueText when using Select2 with ajax to show the displayed name instead of id. For multiple select this needs to be setup as an array.