Search code examples
phpyii2-advanced-app

YII 2 : Adding new attribute inside option select2 kartik widget


i have script using yii 2 :

echo $form->field($model, 'data')->widget(Select2::classname(), [
     'data' => [array_merge(["" => ""], $data)],
     'options' => [
            'placeholder' => 'Select Data Name', 
            'multiple' => false,
     ],
]);

and the result in html :

<select id="storymapdata-data" class="form-control kv-hide input-md" name="Storymapdata[data]">
<optgroup label="0">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
</optgroup>
</select>

and my question, how to add attribute 'data-type' inside option?, i want to like this :

<option value="1" data-type="wms">Option 1</option>
<option value="2" data-type="geojson">Option 2</option>

how?


Solution

  • You can add extra attributes to the option tags through the options options (sounds funny...) configuration.

    <?php
    echo $form->field($model, 'data')->widget(Select2::classname(), [
        'data' => [array_merge(["" => ""], $data)],
        'options' => [
            'placeholder' => 'Select Data Name', 
            'multiple' => false,
            'options' => [
                '1' => ['data-type' => 'mws'],
                '2' => ['data-type' => 'geojson'],
            ],
        ],
    ]);
    

    See the Yii2 documentation for a more detailed explanation.