Monday, 8 October 2012

Button Click Action Using AJAX Toolkit

AJAX can be used to execute any API calls within Javascript without going for VF page and Apex Controller.
AJAX can be used for handling few records as it was delievered via browser, and its performance decreases on larger amounts of data.
This post demonstrates a simple usage of AJAX which executes on a button click.

Whenever an Opportunity is lost, we have nothing to do with the Oppty other than updating its stage to "Closed-Lost".
Let us have a onClick Javascript button on the Opportunity Detail page which updates the Opportunity to Closed-Lost.

Your NameApp SetupCustomizeOpportunitiesButtons and LinksNew
Label: Closed Lost
Name : Closed_Lost
Display Type : Detail Page Button
Behaviour : Execute Javascript
Content Source : onClick Javascript

Paste the following code scripts as below and save,

{!REQUIRESCRIPT("/soap/ajax/25.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/18.0/apex.js")}
sforce.connection.query("SELECT Id,Name,StageName,OwnerId,OrderNumber__c FROM Opportunity where Id= '{!Opportunity.Id}'",{onSuccess: handleSuccess,onFailure: handleFailure});
function handleSuccess(queryresult)
{ 
 try
 {
  records = queryresult.getArray("records");  
  if(records[0].StageName!="Closed Lost")
  { 
   if(confirm("Are you sure?"))
   {       
    records[0].Reason_Lost__c=prompt("Reason for Lost?");
    records[0].StageName='Closed Lost';
    LBox();
    var uprec = sforce.connection.update(records);
    if (uprec[0].getBoolean("success"))  
    {   
    sforce.apex.execute("OpportunityClosed","SendEmail",{OpptyId:'{!Opportunity.Id}',emailtempId:"00XU0000000Yrvm"});
    window.location.reload();
    box.hide();
    }
            }
   else 
   {
    alert(uprec[0]);
   }
  }    
  else
  {
   alert("Opportunity : "+records[0].Name+" is already "+records[0].StageName);
  }
 }
 catch(error)
 {
  alert(error);
 }
}
function handleFailure(error)
{
 alert(error);
}
function LBox() 
{
 var box = new parent.SimpleDialog("sfdc"+Math.random(), true);
 parent.box = box;
 box.setTitle("<img src='/img/icon/opportunities24.png' style='margin:0 5px;'/>"+"Opportunity Closed - Lost...........");
 box.createDialog();
 box.setWidth(500);
 box.setContentInnerHTML("<img src='/img/loading32.gif' alt='' /> Processing"); 
 box.setupDefaultButtons();
 box.show();
}

Add this button to your page layout by drag and drop it to the Custom Buttons Section.
This code fetches the Opportunity record and updates the Stage to "Closed-Lost" with necessary error handling blocks.

1 comment: