Friday 26 October 2012

Sending Email Alerts via AJAX

We can invoke Apex functions from AJAX toolkit using webService methods.
This post demonstrates a way of sending email alerts using a Button functioning based on AJAX.

Please refer my previous post on Button Click Action Using AJAX Toolkit, where Opportunity Stage was updated to "Closed Lost" just by a button click.
This post is actually an extension of the same function, with the addition of sending email alert to the Opportunity Owner that the Opportunity was closed. 

To invoke Apex functions from AJAX,

1. {!REQUIRESCRIPT("/soap/ajax/18.0/apex.js")} need to be included along with the regular {!REQUIRESCRIPT("/soap/ajax/25.0/connection.js")}

2. Invoking Apex functions is possible by using 
   sforce.apex.execute("ApexClassName", "webServiceMethod", {param1,param2..,paramn})

This method invokes the ApexClass which is sending mail using Messaging.SingleEmailMessage.

ButtonClick AJAX code:

{!REQUIRESCRIPT("/soap/ajax/25.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/18.0/apex.js")}

sforce.connection.query("SELECT Id,Name,StageName,OwnerId 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();
}

Note :sforce.debug.trace=true; can be used to display debugging information in a popup window.

Apex class which was invoked by sforce.apex.execute method :

global class OpportunityClosed
{
    webService static void SendEmail(String OpptyId, String emailtempId)
    {
		string targetId=Select OwnerId from Opportunity where Id=:OpptyId].OwnerId;
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();        
        mail.saveAsActivity = false;
        mail.setTargetObjectId(targetId);
        mail.setTemplateId(emailtempid);
        mail.setToAddresses(new String[] { 'xxxxxxxxxxxx@yyy.com' });
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }               
}

No comments:

Post a Comment