Syntax Highlighter JS

Tuesday, June 26, 2012

Custom VF Controller + Javascript: a quick example

Update:   It appears that salesforce has fixed the issue(s) that were causing the need for the variable to be updated via javascript in the post below.   I leave the post in place for unknown future needs but as of 7/6/12 you do not need to put code in place as in the below example - it is handled automatically. 

For the advanced users, this post may be something you have already done but I post it here just in case it helps someone on a google search.

This basic example will take the text from the form, put it in a string variable and re-render it on the screen. What we want to do is modify this example so that the text gets updated upon blur or change of the text field (in addition to the button push).

Salesforce takes care of the variable getting updated upon button push due to our value="{!TextInput}" segment in the apex:inputText line.

Lets start out with a basic visual force page:


And a basic controller: public with sharing class testControllerExt { public string TextInput {get; set;} public testControllerExt() { TextInput = 'Default Text'; } // constructor public pagereference ProcessForm () { return null; } } // main class

To allow the apex method to be called via javascript, we add an action function tag (setup to call the existing ProcessForm Method): You may not want this logic in your work so please notice that I have set immediate="TRUE" to avoid the full save validation that would otherwise normally occur.

This allows us to call the apex method in javascript and pass one parameter that will be assigned to our text field. No default value is assigned.

Now we will use some inline javascript and visualforce to get the element value and pass it in with some code like this: onchange="ProcessFormInJS(document.getElementById('{!$Component.TextInputField}').value);"
Visualforce will now pull in the component ID, then javascript will get the element from that ID, and finally javascript will get the text from the element value and pass it to the javascript function that will remotely call the apex function - with the variable updated.

The final code for the input text looks like this: Additional Notes: With the $component global variable automatically managing your id hierarchy, you won't have to worry about updating this code unless you change the ID of the field being used on the form.

No comments:

Post a Comment