Kartik Select2 - Fill textInput after select

Hello !

Here’s my newbie problem :

I have a view with a Kartik/Select2 widget and a textInput.

Select2 widget show a list of item, and the textInput is only here to show some informations about the selected item.

The Select2 widget work fine, but I don’t know how I must do for fill the textInput after selecting an item in the Select2 widget…

Thanks.

View:


<?php

	echo '<label class="control-label">' . Yii::t('app', 'Item') . '</label>';


	$url = \yii\helpers\Url::to(['maketheitemlist']);


	echo Select2::widget([

		'model' => $model,

		'attribute' => 'itemId',

		'pluginOptions' => [

			'allowClear' => true,

			'tags' => true,

			'ajax' => [

				'url' => $url,

				'dataType' => 'json',

				'data' => new JsExpression('function(params) { return {q:params.term, page: params.page}; }')

			],

		],

	]);

?>


<?= $form->field($model, 'itemId')->textInput(['maxlength' => true, 'readonly'=>true]) ?>



Controller:




public function actionMaketheitemlist($q = null, $id = null) {

	\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

	$out = ['results' => ['id' => '', 'text' => '']];


	if (!is_null($q)) {

		$query = new \yii\db\Query;

		$query->select('itemid AS id, itemname AS text')

			->from('items')

			->where('itemcode LIKE "%' . $q .'%" OR itemname LIKE "%' . $q .'%"')

			->limit(5);

		$command = $query->createCommand();

		$data = $command->queryAll();

		$out['results'] = array_values($data);

	}

	elseif ($id > 0) {

		$out['results'] = ['id' => $id, 'text' => Items::find($id)->itemname];

	}

	return $out;

}



You need to write a Javascript code for the above use case - typically with jQuery you can trigger an ajax call (to fetch value from server) ON CHANGE of the select input and populate your text input based on response via AJAX.