Home Force.com Button action using javascript

We can  update and execute the Objects using  javascript. For that, we need to create button with javascript behavior.

For example, Consider the below snippets of code. Here UpdateController is controller name, updateEnable is the method name and accId: accountId is the arguments. So This button will update the particular field in the object. Assume button name is “Update”

{!REQUIRESCRIPT(“/soap/ajax/24.0/connection.js”)}
{!REQUIRESCRIPT(“/soap/ajax/24.0/apex.js”)}

try{
var accountId='{!Account.Id}’;
var result = sforce.apex.execute(“UpdateController”, “updateEnable”,{accId: accountId});
location.reload();
}
catch(err) {
txt=”There was an error on this page.\n\n”;
txt+=”Error description: ” + err.description + “\n\n”;
txt+=”Click OK to continue.\n\n”;
alert(txt);
}

Consider the below snippets of code and  assume button name is “Enable”. This button will not allow users to do some action before clicking the “update button” which will enable something.

{!REQUIRESCRIPT(“/soap/ajax/20.0/connection.js”)}
sforce.connection.sessionId = ‘{!$Api.Session_ID}’;
try {

var accLst=sforce.connection.query(“SELECT Id, Enable__c from Account where Id = ‘{!Account.Id}'”);
var accRes = accLst.getArray(“records”);

if(accRes.length > 0)
{
if(accRes[0].Enable__c == ‘true’)
{
var url=’https://ap1.salesforce.com/’ +'{!Account.Id}’;
window.location.href=url;
}
else
{
alert(‘Please Click the Enable Button before you click on “Update”‘);
}
}

} catch(e) {
alert(‘Error:::::’ + e);
}

Below is controller coding.

global class UpdateController {

webService static string updateEnable(List<Id> accId){
try{
System.debug(‘Id–>’+accId);
if(accId != NULL && accId.size() > 0)
{
Account accUpdate = [SELECT Id, Enable__c from Account where Id =:accId];
accUpdate.Enable__c = ‘true’;
update accUpdate;
return ‘Updated successfully’;
}
}
catch(exception e){}

return null;
}

}

You may also like

Leave a Comment