rniemeyer / knockout-jqAutocomplete

knockout-jqAutocomplete is a Knockout.js plugin designed to work with jQuery UI's autocomplete widget.
MIT License
49 stars 20 forks source link

How do you pre-populate this control? #26

Closed gregveres closed 7 years ago

gregveres commented 7 years ago

Hi,

generally I assume that everybody has run across an issue before me, but I can't find an example of what I need to do.

I have a dialog box where one of the fields lets the user type in a name. This uses the jqAutocomplete binding to go to the server and fetch the list of names. What comes back is an array of { Id, Name }

I display the Name using the labelProp and the id is the valueProp. InputProp is also Name. ValueProp is tied to a ko observable in my model.

This works great when I create the database entry with the dialog.

Now I am working on editing that database entry. When I edit, I need to have the jqAutocomplete box show the Name field again, but my problem is that when I set my ko observable, I get Id showing up in the jqAutocomplete field. I know I haven't set the name anywhere for jqAutocomplete to read it, but I can't figure out how to do this. I can have access to the name, but how does one reconstruct the UI for an edit dialog using jqAutocomplete?

Thanks Greg

gregveres commented 7 years ago

What I did to get this working is to move to using the dataValue field. In my typescript model, I keep track of two objects rather than just one. I define my member as { Id: number, Name: string }. Then in my view model I keep track of:

member: memberStruct memberName: string

then when I instantiate the jqAutocomplete binding, I create it with:

data-bind="jqAuto: { source: getMemberList, value: memberName, inputProp: 'Name', labelProp: 'Name', valueProp: 'Name', dataValue: member }

where getMemberList is a function on my viewmodel. Notice I use Name for all the fields and I set dataValue to the complete member field.

This works great. The user only sees and interacts with the name but under the covers the component keeps track of the full member with the Id.

There is a bug with the current implementation but I will create another issue for that and open a PR with my fix.

Hope this helps somebody in the future.