yii2 select2 chaining

Hi,

I am using kartik extensions.

I have master-detail in Budget and BudgetDetail. When adding BudgetDetail in Budget, several fields must be filled in. one of the field is item. I use select2 to display the item lists. my question is how can I update the field unit when an item is selected?

my getItemLists() is something like this




    // List all active items

    public static function getItemLists() {

        $result = [];

        $items = Item::find()->active()->orderBy('name')->all();


        foreach ($items as $item) {

            $result[] = [

                'id' => $item->id,

                'text' => $item->name,

                'unit' => $item->baseUnit

            ];

        }


        return ['result' => $result];

    }



in the form view file:





    <div class="row">

        <span class="col-md-12">

            <?=

            $form->field($model, 'itemFk')->widget(Select2::classname(), [

//                'data' => ArrayHelper::map(Item::find()->active()->all(), 'id', 'name'),

                'data' => Item::getItemLists(),

                'options' => ['placeholder' => Yii::t('app', 'Select an item ...')],

                'pluginOptions' => [

                    'allowClear' => true

                ],

                'pluginEvents' => [

                    'select2:select' => 'function(e) { $("#BudgetDetail_unit").val(e.params.data.unit); }',

                ],

            ]);

            ?>

        </span>

    </div>



It does not return the value as expected. The unit is not being updated while the options become weird

Can someone help?

I can do this using automcomplete chaining in yii 1.1

TIA

Daniel

My current workaround is like this,




    // List all active items

    public static function getItemLists() {

        $result = [];

        $items = Item::find()->active()->orderBy('name')->all();


        foreach ($items as $item) {

            $result[$item->id] = $item->name . ' | ' . $item->baseUnit;

        }


        return $result;

    }



and the view file




<div class="row">

        <span class="col-md-12">

            <?=

            $form->field($model, 'itemFk')->widget(Select2::classname(), [

//                'data' => ArrayHelper::map(Item::find()->active()->all(), 'id', 'name'),

                'data' => Item::getItemLists(),

                'options' => ['placeholder' => Yii::t('app', 'Select an item ...')],

                'pluginOptions' => [

                    'allowClear' => true

                ],

                'pluginEvents' => [

                    'select2:select' => 'function(e) { '

                    . 'var txt = e.params.data.text;'

                    . 'var txtArr = txt.split("|");'

                    . '$("#budgetdetail-unit").val(txtArr[1].trim()); '

                    . '}',

                ],

            ]);

            ?>

        </span>

    </div>



Does anyone have better solution?