In my Grails project I have a field that allows me to select between a list.
After user has selected a value, I store the id of the related object.
I would like that, after storing the id, I get a value related to the object with that id and show it into another input field.
Here is the javascript that I use to store the id:
$("#patient_textField").autocomplete({
source: data,
select: function (event, ui){
$('#patient_id').val(ui.item.id);
}
});
I've created a function in controller that allows me to get the value that I need to show into the second input field
def getPhoneNumberFromPatientId(int patientID)
{
int phone = Patient.findById(patientID).phone_1
if(phone == null)
phone = Patient.findById(patientID).phone_2
return phone
}
How can I solve it?
You need to use AJAX to accomplish what you want. In Grails you have some taglibs that are very useful to execute an AJAX call.
An example is g:remoteFunction. This taglib allows you to execute an AJAX call and update the content of an HTML element. It's a very useful taglib!
For this question I've wrote an example that allows the user to select an option in a list (HTML Select) and update the content of a textArea based on the user selection. The update is performed by an AJAX call.
Main GSP (test.gsp)
The AJAX call happens in the onchange event of g:select. For simplicity I omit some attributes of g:select as optionValue and optionKey.
This GSP is rendered by the following action:
As you can see, this action returns an model to the above GSP that must be called test.gsp since this is name of the action. The variable options is the list of elements that could be selected by the user.
Remote Function
The remote function calls an action called getPhoneNumberFromPatientId and on the onSuccess event updates the textArea called value. The update is performed using JQuery.
See below the action getPhoneNumberFromPatientId:
The actions above doesn't return, the actions render the content. It's a very importante difference. See this answer to understand the difference: Grails updating values in form using Ajax
Basically when you're working with AJAX call you'll render the content. The content could be a variable (as above), an HTML snippet or a GSP template.
Please, check the source code of your page (in your browser) to understand that your g:remoteFunction was rendered as a JQuery AJAX call.
Bonus
After the AJAX call I set the focus on the textArea. This is done using JQuery too. See the end of the onchange event to understand this part.