Showing posts with label Remote Action in Visualforce page. Show all posts
Showing posts with label Remote Action in Visualforce page. Show all posts

Friday, June 1, 2012

Remote Action in Visualforce page


Remote Action in Visual force page:
   JavaScript remoting in Visualforce provides support for some methods in Apex controllers to be called via JavaScript.
• namespace is your organization's namespace. This is only required if the class comes from an installed packaged.
• controller is the name of your Apex controller- MyJSControllers
• method is the name of the Apex method you're calling- getAccount
• params is comma–separated list of parameters that your method takes- accountNameJS
• callbackFunction is the name of the function that handles the response from the controller. It returns the status of the call and the method result.- function
• escape defines whether your response should be escaped (by default, true) or not (false)- {escape:true}

·        JavaScript remoting:
- pass parameters
- provides a callback
·        The <apex:actionFunction> tag:
- specify rerender targets
- submits the form

VF Code:
<apex:page controller="MyJSControllers">
<script type="text/javascript">
function getAccountJS() {
var accountNameJS = document.getElementById(' accName ').value;
MyJSControllers.getAccount( accountNameJS, function(result, event){
if (event.status) {
// demonstrates how to get ID for HTML and Visualforce tags
document.getElementById('accid').innerHTML = result.Id
document.getElementById("{!$Component.theBlock.thePageBlockSection.theSecondItem.accEmployees}").innerHTML = result.NumberOfEmployees;
} else if (event.type === 'exception') {
document.getElementById("errors-js").innerHTML = event.message;
} else {
document.getElementById("errors-js").innerHTML = event.message;
}
}, {escape:true});
}
</script>
Account Name :<input id="accName" type="text" />
<button onclick="getAccountJS()">Get Account</button>
<div id="errors-js"> </div>
<apex:pageBlock id="theBlock">
<apex:pageBlockSection id="thePageBlockSection" columns="2">
<apex:pageBlockSectionItem id="theFirstItem">
<span id="accid" />
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem id="theSecondItem">
<apex:outputText id="accEmployees" />
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:page>

*Note: This class will save only on Salesforce.com API version 21.

Controller class code:
public global with sharing class MyJSControllers {
public String accountName { get; set; }
public static Account account { get; set; }
public MyJSControllers() { }

@RemoteAction
global static Account getAccount(String accountName) {
account = [select id, name, phone, type, numberofemployees from
Account where name = :accountName ];
return account;
}
}