user3427013
user3427013

Reputation: 1099

Yii 2 Select2 kartik with custom html

How to translate this into Yii2 select2 kartik widget? I think the "data" attribute from the select2 kartik widget only allows for id -> text. Is there a way to get this done using the widget?

var data = [{
   id: 0,
   text: 'enhancement',
    html: '<div style="color:green">enhancement</div>'
}, {
   id: 1,
   text: 'bug',
    html: '<div style="color:red">bug</div><div><small>This is some small text on a new line</small></div>'
}];

function template(data) {
    return data.html;
}

$("select").select2({
   data: data,
   templateResult: template,
   escapeMarkup: function(m) {
      return m;
   }
});

Upvotes: 0

Views: 3278

Answers (1)

user3427013
user3427013

Reputation: 1099

The solution is to use the "data" attribute within the "pluginOptions" array:

echo $form->field($model, 'id_customer')->label(false)->widget(Select2::classname(), [
    'data' => [],
    'options' => ['placeholder' => Yii::t('app', 'Select a customer')],
    'pluginOptions' => [
        'allowClear' => true,
        'data' => $customerList,
        'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
        'templateResult' => new JsExpression('formatTemplateResult'),
        'templateSelection' => new JsExpression('formatSelection'),
    ],
]);

Upvotes: 3

Related Questions