Yii2 Typeahead Widget (Kartik)

Hi,

I have a search field which uses the typeahead-widget from kartik. I am wondering now, how to access different values from a search-item than the display name. This is my search-field:




// $data = array with ID => DisplayName

Typeahead::widget([

	'name' => 'header-search',

	'options' => ['placeholder' => 'My test search field'],

	'pluginOptions' => ['highlight' => true],

	'dataset' => [

		[

			'local' => $data,

			'limit' => 10

		]

	],

	'pluginEvents' => [

		'typeahead:selected' => 'function() {window.open("' . LinkHelper::getHomeUrl() . '" + $(this).typeahead("val"),"_self")}',

		'typeahead:autocompleted' => 'function() {window.open("' . LinkHelper::getHomeUrl() . '" + $(this).typeahead("val"),"_self")}'

	]

]);



The question is, how can I access the ID-field of a search-item so that I can use the ID to generate the URL where to go when selecting an item.

Can you implement something like a custom adapter?

Does anybody know how to do this?

Thank you very much!

The core typeahead plugin does not support it out of the box (storing the id and showing the name). If you want a prebuilt functionality like this, which does this faster, ideally you should be looking at something like my Select2 widget.

Having said that, with the typeahead you can write your own javascript code, to do something like this e.g. using the updater property in the pluginOptions to fetch the id and store it in a hidden field on the same form.

I will try and see if I can enhance this in the plugin (will require some rework over the twitter typeahead JS) – OR Create a wiki/web tip when I get time.

‘pluginEvents’ => [

                    'typeahead:selected' => 'function(obj, datum, name) {alert(datum.ID)}',


                ]

now here you can use datum.#fieldName# which is from search query