Yii2 Kartik Select2 - Template to formatting each list element

Hi all, i’m looking to Kartik Select2 Page

In particular i want to add an image to each element of the list like the example:

use kartik\widgets\Select2;

use yii\web\JsExpression;

use yii\bootstrap\Modal;


// Templating example of formatting each list element

$url = \Yii::$app->urlManager->baseUrl . '/images/flags/';

$format = <<< SCRIPT

function format(state) {

    if (!state.id) return state.text; // optgroup

    src = '$url' +  state.id.toLowerCase() + '.png'

    return '<img class="flag" src="' + src + '"/>' + state.text;



$escape = new JsExpression("function(m) { return m; }");

$this->registerJs($format, View::POS_HEAD);

echo '<label class="control-label">Provinces</label>';

echo Select2::widget([

    'name' => 'state_12',

    'data' => $data,

    'options' => ['placeholder' => 'Select a state ...'],

    'pluginOptions' => [

        'templateResult' => new JsExpression('format'),

        'templateSelection' => new JsExpression('format'),

        'escapeMarkup' => $escape,

        'allowClear' => true




In this example as you can see, the filename with the image of the state has the same name of the state.id

src = '$url' +  state.id.toLowerCase() + '.png'

and it’s simple to use.

But my problem is that the filename for each state is different and is stored in my db. For example i have:

//Active Record

$state->id  //my state id

$state->img // the name of the image i want 

How can i pass the right image name for each element of the list to the script?

Thank’s for any help.

anyone can help me with this problem?


hi , i know this is a late response, but you can do this by adding extra attribute to your option tag.

for example:

<option data-imgsrc='srchere'></option>

you should pass that from your controller to your view.

and in the template result you can get the value of the image source

function format(state) {

    src= &#036;(state.element).data('srchere') + '.png'[size=2];[/size]

       [color=#000088][size=2]return[/size][/color][size=2] [/size][color=#008800][size=2]'&lt;img class=&quot;flag&quot; src=&quot;'[/size][/color][size=2] [/size][color=#666600][size=2]+[/size][/color][size=2] [/size][color=#666600][size=2][color=#000000][size=3]src[/size][/color]+[/size][/color][size=2] [/size][color=#008800][size=2]'&quot;/&gt;'[/size][/color][size=2] [/size][color=#666600][size=2]+[/size][/color][size=2] state[/size][color=#666600][size=2].[/size][/color][size=2]text[/size][color=#666600][size=2];[/size][/color]