I have a form that a user can fill out that maps to an object in Rails.
One of the fields in the form auto-completes to instances of the object that have already been created.
I am trying to make it so that if an autocomplete option is selected on that one field, it will fill out the entire form based on that instance’s data.
I am assuming that the best way for this to be done is through an ajax call once the autocomplete is selected which grabs all the data and re-renders the form? That seems like it will create an undesirable delay between when the field is auto-completed and the form is auto-filled.
Is it then possible to have all the necessary data in the auto-complete data and auto-fill the form immediately?
If you want instant access to your data, you need to preload it. Many ways to go about doing so. But considering you’re using AJAX autocomplete (assumption on my part), it would seem that you’ve already decided to live with that tiny bit of latency as the AJAX request roundtrips to the server. Given that, once the auto-complete field value is selected by the user, just load the corresponding data via AJAX at that moment. If the delay is too long for your tastes, consider a “spinner” graphic. This is such a common paradigm on the ‘Net these days, nobody will think twice if it takes < .5 second.
As for the form being filled – at some point you’ll need to iterate over the object or the form fields and populate them with their corresponding values from the object. Using naming conventions here can help you, consider for example having your form’s inputs have class names that correspond to instance variable names in your object, such as:
Then, your form might have fields like:
Finally, once you’ve matched an instance of your object to what the user has entered, do:
Contrived example of course and many ways to go about it, but that might help you get started.
Cheers