Search code examples
phpyii2semantic-uiyii-extensionsyii2-basic-app

Yii2. Add icons to DropdownList widget items


How to add icons to DropdownList widget items?

I want to have this (fronted-dev took this right from semantic-ui)

enter image description here

but after using widget it's quite hard to add an icon.

Here is my code and output

<?php $items = [
            '123' => '<i class="af flag"></i>aaa',
            '124' => 'bbb',
            '345' => 'ccc',
        ]
        ?>
        <?=$form->field($model, 'country', [
            'template' => '{label} <div class="field">{input}{error}{hint}</div>',
        ])->dropDownList($items, ['class' => 'ui dropdown selection', 'prompt' => 'Select Country']);?>

enter image description here

What code snippet/library could help me to perform this task? I need any implementation, that could be used as ActiveField.

[UPD]

scaisEdge option gave this enter image description here


Solution

  • DropDownlist is an implementation of Basic SELECT Dropdown, which is a basic UI control (HTML content is not covered). You need a more advanced Dropdown selector like Select2 Component (http://demos.krajee.com/widget-details/select2) and use the widget() method to call the contruction of the control using that Class.

    $form->field($model, 'country', [
                'template' => '{label} <div class="field">{input}{error}{hint}</div>',
         ])->widget(Select2::classname(),[
        'data' => $data,
        'options' => ['placeholder' => 'Select a state ...'],
        'pluginOptions' => [
            'templateResult' => new JsExpression("function format(state) {  return '<img src=flag.png >';}"),
            'templateSelection' => new JsExpression("function format(state) {  return '<img src=flag.png >';}"),
            'escapeMarkup' => $escape,
            'allowClear' => true
        ],
    ]);
    

    See some examples in http://demos.krajee.com/widget-details/select2#usage-advanced