Salesforce Developer Javascript Remoting Example2
salesforce-developer-javascript-remoting
// Salesforce - Developer - JavaScript Remoting - Example 2 (Form submission):
Consider the following Visualforce page:
<apex:page standardController="Account"
extensions="JSRemotingFormSubmitController" id="page">
<script type="text/javascript">
// Method to update information on the Account bound to the page by the
// standardController
// Sends parameters: Account Id, Description, Website, and Phone to the
// controller
function submitForm() {
var descriptionText = document.getElementById('descriptionText').value;
var websiteText = document.getElementById('websiteText').value;
var phoneText = document.getElementById('phoneText').value;
JSRemotingFormSubmitController.doSubmitForm(
'{!Account.Id}', descriptionText, websiteText, phoneText,
function(result, event) {
if(event.type === 'exception') {
console.log("exception");
console.log(event);
} else if (event.status) {
console.log(result);
if(result == 'Success') {
window.location.reload();
} else {
alert(result);
}
} else {
console.log(event.message);
}
}
);
}
</script>
<h2>Javascript Remoting Form Submission Example </h2> <br /> <br />
Enter the updated information for <strong>
<apex:outputText value="{!Account.Name}" /></strong> <br />
Description:
<input type="text" value="{!Account.Description}" size="50"
id="descriptionText"/> <br />
Website URL:
<input type="text" value="{!Account.Website}" size="40"
id="websiteText"/> <br />
Phone Number:
<input type="text" value="{!Account.Phone}" size="18"
id="phoneText"/> <br />
<button onclick="submitForm()">Submit Form</button>
</apex:page>
and the corresponding controller:
global with sharing class JSRemotingFormSubmitController {
public JSRemotingFormSubmitController(ApexPages.StandardController c) {
}
@RemoteAction
public static String doSubmitForm(String acctId, String description,
String website, String phone) {
if(acctId != null) {
Account acct = getAccount(acctId);
if(acct != null) {
//DO VALIDATION HERE@!@@@!!!@!@!!@1111ONE
acct.Description = description;
acct.Website = website;
acct.Phone = phone;
update acct;
return 'Success';
} else {
return 'Account could not be found';
}
} else {
return 'Account Id was null';
}
}
private static Account getAccount(String acctId) {
list<Account> accounts = [SELECT Id, Name, Counter__c
FROM Account
WHERE Id =: acctId];
if(accounts.isEmpty()) {
return null;
} else {
return accounts[0];
}
}
}
When this page is loaded (make sure to use ?id=[account_Id] after the page name
in the URL).
When you click the Submit Form button, the javascript method submitForm() is
called. The values of the input elements is determined, and the call to the
controller is made. You can see how we’re sending all of the parameters the
controller is expecting in the method declaration of the controller.
After the method executes, we do some validation to make sure we didn’t hit an
error state.
page revision: 1, last edited: 22 Jan 2017 06:49