0% found this document useful (0 votes)
357 views12 pages

Apex Triggers for Beginners

The document provides code samples for basic Apex trigger patterns that update a field on an object when it is inserted. It includes a before insert trigger that updates the HasOptedOutOfEmail field on Contact, and an after insert trigger that does the same using a list. It also includes a test class to test both triggers. The document then discusses using unit tests to prevent fields from being deleted by testing their usage, and provides a code sample for a trigger that updates a master object when a child record is inserted or updated.

Uploaded by

MahendraKumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
357 views12 pages

Apex Triggers for Beginners

The document provides code samples for basic Apex trigger patterns that update a field on an object when it is inserted. It includes a before insert trigger that updates the HasOptedOutOfEmail field on Contact, and an after insert trigger that does the same using a list. It also includes a test class to test both triggers. The document then discusses using unit tests to prevent fields from being deleted by testing their usage, and provides a code sample for a trigger that updates a master object when a child record is inserted or updated.

Uploaded by

MahendraKumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

3/4/2016

CodeSample|TeachMeSalesforce

TeachMeSalesforce
Acommunityapproachtolearningsalesforce.com

ArchivefortheCodeSampleCategory
SimplestApexTriggerPatterns
leaveacomment
BecausesometimesyoujustwanttoseethebasicprogrammingpatternsforApexandreverseengineerthemtofityourneeds.
Thesetwoarethemostbasictriggerpatterns.Theybothdothesamething:setafieldsvalueonarecordwhenthatrecordisadded
toSalesforce.Itonlyhappensoninsert,notonupdatebecausethatsslightlylesssimple(andadifferentpost).Theonlydifferenceis
onedoesitBeforeInsertandonedoesitAfterInsert.Why?Becausetheycan.Maybesomedaywelldiscussherewhyyouuseone
ortheotherbuttodaywejustwantcodethatworks,sohereyougo:
TriggerContactBeforeTriggeronContact(beforeinsert){
for(Contactc:Trigger.new){
c.HasOptedOutOfEmail=true;
}
}
TriggerContactAfterTriggeronContact(afterinsert){
ListconList=newList();

for(ContactconInTrigger:trigger.new){
Contactc=newContact(Id=conInTrigger.Id,HasOptedOutOfEmail=true);
conList.add(c);
}
updateconList;
}

AndofcourseanythingyouwanttouseinProductionneedsatestclass,sohereyougo,onethatworksforboth!
@isTest
publicClassTestContactTrigger{
publicstatictestMethodvoidtestContactInsert(){

ContactaNewContact=newContact(LastName='qwerty');

InsertaNewContact;

ContacttheInsertedContact=[SelectHasOptedOutOfEmailfromContactlimit1];

System.assert(theInsertedContact.HasOptedOutOfEmail);

}
}

WrittenbyAlwaysThinkin
February28,2016at4:53pm
PostedinApex,Beginner,CodeSample,Trigger,Uncategorized

UnitTests:NotJustforDevIdea1
leaveacomment
Unittestsoffermuchmorethanjustthemeanstoget75%+codecoverage,andtheycanbeusedtoprotectmorethanjustApex.
ReadtheintrotothisseriesinIdea0.
Ourfirstexampleisthesimplest:protectingfieldsthatyoudontwantdeleted.AusecaseforthisisExternalIntegrationsthatrelyon
https://teachmesalesforce.wordpress.com/category/codesample/

1/13

3/4/2016

CodeSample|TeachMeSalesforce

Salesforcefields.Ifsomeonetriestodeletethefields,youwanttoensurethattheyarealertedtotheimpact.Byincludingthefields
CurrentGeneratorsandSICCodeintheexampleUnitTestbelow,anattempttodeletethefieldswillthrowanerrorreferencingthe
unittest.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

@isTest
privateclassUnitTest1{
statictestMethodvoidprotectFields(){

/*CreateanewLead,populatinganyFieldsyouneedtoprotect
*Inthiscase,wewanttoensureCurrentGeneratorsandSICCodecannotbedeleted
*orthefieldtypechangedbyincludingtheminthisApexUnitTest
*/
Leadl=newLead(Company='TestLead',
LastName='LeadLastName',
CurrentGenerators__c='GeneratorX',
SICCode__c='1234ABC');
insertl;
}
}

Letsdescribewhatshappeninghere.
Westartoffwiththeallimportant@isTestflag.ThistellsSalesforcethattheApexClasscontainsonlytestMethods.Thatmeans
nothingyoudointheClasswillbesavedtotheserver,andwillnotdeleteorchangeanythingontheserver.Italsomeansyoucannot
usemostrecordsthatexistontheserver,soyouhavetocreateyourowntestrecords.
@isTestmeansthatSalesforcewillrecognizeitasatestClass,andwhenyouRunAllTests,itwillknowtorunthistesttoo.
NextistheClassName,UnitTest1anditsaccessmodifierissettoprivate.AccessmodifiersareirrelevantforUnitTests,privateis
thedefault.
TheactualtestMethodhereisprotectFields().Yourtestexistsbetweenthecurlybraces{}.Hereyoumustcreateyourtestrecords
andperformanyactionsyouwanttested.ThecriticalitemhereistestMethodwhichensuresthatSalesforcerecognizesthemethod
asperformingtests.Withoutthis,Salesforcewillnotreportatestfailureregardlessoftheoutcome.
InthiscasewearecreatingaLead.WeareusingstandardApexcodetocreateaLead,topopulatefieldsonthatLead,andfinallyto
useDMLtoinserttheLead.RequiredfieldsandValidationRuleswillgetenforcedwhenyoucreatetheLead,sobesuretoinclude
anyfieldsaffectedbythem.
OncethisUnitTestissavedtotheserver,anyattempttodeletethefieldorchangeitsdatatypewillbeblockedwithareferenceto
thisUnitTest.
Forthislimitedscenario,thatsallweneed!
WrittenbyAlwaysThinkin
August3,2014at3:53pm
PostedinApex,CodeSample,Intermediate
TaggedwithApex,UnitTest

SalesforceTriggerwhenRollupsSummariesNotPossible
with6comments
MasterDetailsrelationshipsinForce.comareveryhandybutdontfiteveryscenario.Forinstance,itsnotpossibletoimplementa
rollupsummaryonformulafieldortextfields.Heresasmalltriggerthatyoucanuseforastarterforthesetypesofsituations.The
codeforeachclassisavailableatGitHubforyourforkingpleasure.
Soheresthe(notveryuseful)usecase.SalesOrderistheMasterobjectwhichcanhavemultipleSalesOrderItems(detailobject).
TheSalesOrderItemhasaprimaryBooleanfieldandapurchasedcountryfield.EachtimeSalesOrderItemsareinsertedor
updated,iftheSalesOrderItemismarkedasprimarythenthevalueofpurchasedcountryiswrittenintotheprimarycountry
fieldontheSalesOrder.ImassumingthattherecanonlybeoneSalesOrderItemperSalesOrderthatismarkedas
primary.EssentiallythisisjustaquickreferenceontheSalesOrdertoseewhichcountryisprimaryonanyofthemultipleSales
OrderItems.Notveryusefulbutillustrative.
https://teachmesalesforce.wordpress.com/category/codesample/

2/13

3/4/2016

CodeSample|TeachMeSalesforce

ThecodeisbrokendownintoaTriggerandanApexhandlerclassthatimplementstheactualfunctionality.Itsbestpracticeto
onlyhaveonetriggerforeachobjectandtoavoidcomplexlogicintriggers.Tosimplifytestingandresuse,triggersshoulddelegate
toApexclasseswhichcontaintheactualexecutionlogic.SeeMikeLeachsexcellenttriggertemplateformoreinfo.
SalesOrderItemTrigger(sourceonGitHub)ImplementstriggerfunctionalityforSalesOrderItems.Delegatesresponsibilityto
SalesOrderItemTriggerHandler.
triggerSalesOrderItemTriggeronSales_Order_Item__c(afterinsert,afterupdate){
SalesOrderItemTriggerHandlerhandler=newSalesOrderItemTriggerHandler();

if(Trigger.isInsert&&Trigger.isAfter){
handler.OnAfterInsert(Trigger.new);

}elseif(Trigger.isUpdate&&Trigger.isAfter){
handler.OnAfterUpdate(Trigger.old,Trigger.new,Trigger.oldMap,Trigger.newMap);

}
}

SalesOrderItemTriggerHandler(sourceonGitHub)Implementsthefunctionalityforthesalesorderitemtriggerafterinsertand
afterupdate.Looksateachsalesorderitemandifitismarkedasprimary_item__cthenmovestheprimary_country__cvaluefrom
thesalesorderitemtotheassociatedsalesordersprimary_country__cfield.
publicwithsharingclassSalesOrderItemTriggerHandler{
//updatetheprimarycountrywhennewrecordsareinsertedfromtrigger
publicvoidOnAfterInsert(ListnewRecords){
updatePrimaryCountry(newRecords);
}

//updatetheprimarycountrywhenrecordsareupdatedfromtrigger
publicvoidOnAfterUpdate(ListoldRecords,
ListupdatedRecords,MapoldMap,
MapnewMap){
updatePrimaryCountry(updatedRecords);
}

//updatesthesalesorderwiththeprimarypurchasedcountryfortheitem
privatevoidupdatePrimaryCountry(ListnewRecords){

//createanewmaptoholdthesalesorderid/countryvalues
MapsalesOrderCountryMap=newMap();

//ifanitemismarkedasprimary,addthepurchasedcountry
//tothemapwherethesalesorderidisthekey
for(Sales_Order_Item__csoi:newRecords){
if(soi.Primary_Item__c)
salesOrderCountryMap.put(soi.Sales_Order__c,soi.Purchased_Country__c);
}
https://teachmesalesforce.wordpress.com/category/codesample/

3/13

3/4/2016

CodeSample|TeachMeSalesforce

//queryforthesaleordersinthecontexttoupdate
Listorders=[selectid,Primary_Country__cfromSales_Order__c
whereidIN:salesOrderCountryMap.keyset()];

//addtheprimarycountrytothesalesorder.finditinthemap
//usingthesalesorder'sidasthekey
for(Sales_Order__cso:orders)
so.Primary_Country__c=salesOrderCountryMap.get(so.id);

//committherecords
updateorders;

}
}

Test_SalesOrderItemTriggerHandler(sourceonGitHub)TestclassforSalesOrderItemTriggerand
SalesOrderItemTriggerHandler.Achieves100%codecoverage.
@isTest
privateclassTest_SalesOrderItemTriggerHandler{
privatestaticSales_Order__cso1;
privatestaticSales_Order__cso2;
//setupourdataforeachtestmethod
static{

Contactc=newContact(firstname='test',lastname='test',email='no@email.com');

insertc;

so1=newSales_Order__c(name='test1',Delivery_Name__c=c.id);
so2=newSales_Order__c(name='test2',Delivery_Name__c=c.id);

insertnewList{so1,so2};

}
statictestMethodvoidtestNewRecords(){

Sales_Order_Item__csoi1=newSales_Order_Item__c();
soi1.Sales_Order__c=so1.id;
soi1.Quantity__c=1;
soi1.Description__c='test';
soi1.Purchased_Country__c='Germany';

Sales_Order_Item__csoi2=newSales_Order_Item__c();
soi2.Sales_Order__c=so1.id;
soi2.Quantity__c=1;
soi2.Description__c='test';
soi2.Purchased_Country__c='France';
soi2.Primary_Item__c=true;

Sales_Order_Item__csoi3=newSales_Order_Item__c();
soi3.Sales_Order__c=so2.id;
soi3.Quantity__c=1;
soi3.Description__c='test';
soi3.Purchased_Country__c='Germany';
soi3.Primary_Item__c=true;

Sales_Order_Item__csoi4=newSales_Order_Item__c();
soi4.Sales_Order__c=so2.id;
soi4.Quantity__c=1;
soi4.Description__c='test';
soi4.Purchased_Country__c='Germany';

Sales_Order_Item__csoi5=newSales_Order_Item__c();
soi5.Sales_Order__c=so2.id;
soi5.Quantity__c=1;
soi5.Description__c='test';
soi5.Purchased_Country__c='Italy';

insertnewList{soi1,soi2,soi3,soi4,soi5};

System.assertEquals(2,[selectcount()fromSales_Order_Item__cwhereSales_Order__c=:so1.id]);
https://teachmesalesforce.wordpress.com/category/codesample/

4/13

3/4/2016

CodeSample|TeachMeSalesforce

System.assertEquals(3,[selectcount()fromSales_Order_Item__cwhereSales_Order__c=:so2.id]);

System.assertEquals('France',[selectprimary_country__cfromSales_Order__cwhereid=:so1.id].primary_country__c);
System.assertEquals('Germany',[selectprimary_country__cfromSales_Order__cwhereid=:so2.id].primary_country__c);

statictestMethodvoidtestUpdatedRecords(){

Sales_Order_Item__csoi1=newSales_Order_Item__c();
soi1.Sales_Order__c=so1.id;
soi1.Quantity__c=1;
soi1.Description__c='test';
soi1.Purchased_Country__c='Germany';

Sales_Order_Item__csoi2=newSales_Order_Item__c();
soi2.Sales_Order__c=so1.id;
soi2.Quantity__c=1;
soi2.Description__c='test';
soi2.Purchased_Country__c='France';
soi2.Primary_Item__c=true;

insertnewList{soi1,soi2};

//assertthatthecountry=France
System.assertEquals('France',[selectprimary_country__cfromSales_Order__cwhereid=:so1.id].primary_country__c);

Listitems=[selectid,purchased_country__cfromSales_Order_Item__c
whereSales_Order__c=:so1.idandprimary_item__c=true];
//changetheprimarycountryonthesalesorderitem.shouldtriggerupdate
items.get(0).purchased_country__c='Denmark';

updateitems;
//assertthatthecountrywassuccessfullychangedtoDenmark
System.assertEquals('Denmark',[selectprimary_country__cfromSales_Order__cwhereid=:so1.id].primary_country__c);

WrittenbyJeffDouglas
August23,2011at9:00am
PostedinApex,CodeSample,Trigger

JavaScriptRemoting
with2comments
Oneofthemajorenhancementsfromvisualforcethisrelease(Summer11)andmyfavoriteisJavaScriptremoting.
JavaScriptRemotingistheabilitytoinvokeapexclassmethodfromjavascriptembeddedinavisualforcepage.JavaScriptRemoting
isnowavailableaftersummer11release.
Hereisaquickexample:wehaveaApexclasswhichdefinesagetAccountmethod.
globalwithsharingclassMyJSRemoting
{
publicstaticAccountaccount{get;set;}
@RemoteAction
globalstaticAccountgetAccount(StringaccountName){
account=[selectid,name,phone,type,numberofemployeesfrom
Accountwherename=:accountNamelimit1];
returnaccount;
}
}

Thismethodishaving@RemoteActionannotationmakingitavailabletobecalledfromavisualforcepage.Nowinourvisualforce
pagewehaveascripttagsetwhichishowweembedjavascriptwithinvisualforcepages.
<apex:pagecontroller="MyJSRemoting">
https://teachmesalesforce.wordpress.com/category/codesample/

5/13

3/4/2016

CodeSample|TeachMeSalesforce

<scripttype="text/javascript">
functiongetAccountJS(){
varaccountNameJS=document.getElementById('accountname').value;
ankit.MyJSRemoting.getAccount(accountNameJS,function(result,event)
{
if(event.status)
{
document.getElementById("{!$Component.theBlock.pbs.pbsi2.accId}")
.innerHTML=result.Id;
document.getElementById("{!$Component.theBlock.pbs.pbsi1.name}")
.innerHTML=result.Name;
}
},{escape:true});
}
</script>
<inputid="accountname"type="text">
<buttononclick="getAccountJS();">GetAccount</button>
<apex:pageblockid="theBlock">
<apex:pageblocksectioncolumns="2"id="pbs">
<apex:pageblocksectionitemid="pbsi1">
<apex:outputtextid="name">
</apex:outputtext></apex:pageblocksectionitem>
<apex:pageblocksectionitemid="pbsi2">
<apex:outputtextid="accId">
</apex:outputtext></apex:pageblocksectionitem>
</apex:pageblocksection>
</apex:pageblock>
</apex:page>

ThisJavaScriptcodetheninvokesthegetAccountmethodintheapexclasstotakeaction.
PleasenoteIhaveusednamespaceankit.MyJSRemotingasthereisanamespaceregisteredonmyorganization.
JavaScriptRemotingisthefeaturewhichisprimarilybeusedbydevelopersandwillallowthemtocreatericherandmoreinteractive
userinterfacesthateveryonewillbenefitfrom.
Inparticular,letsdeveloperscreaterichjavascriptbaseduserinterfacesbyinvokingapexcontrollermethodswithinJavaScriptcode.
JavaScriptistypicallyusedtorendersmallpartsofuserinterface.ResultfromaJavascriptremotingcallaremuchfasterthenusing
atypicalvisualforcereRendermodel,developerscanprovidemoreinstantfeedbacktotheuser.Thisisbecauseremotingcallsare
stateless.MeansonlydataissetbackandforthinsteadalotofbulkyHTML.
AdditionalVisualforceenhancements:
1)FilteredLookupviaVisualforce.
2)Inlineeditingforrichtextareafield.
3)FieldSetpropertyaccessors.
ThisisacrossposttomyBlog.
WrittenbyAnkitArora(forceguru)
June19,2011at4:33pm
PostedinAdvanced,Apex,CodeSample,Visualforce

VisualforceCodeGenerator
with9comments
ThisisacrosspostfrommyBlogPost.
Weknowhowmuchimportantrolevisualforceplaysinourapplication.Therearemanyinstancewhereweneedtocreatea
https://teachmesalesforce.wordpress.com/category/codesample/

6/13

3/4/2016

CodeSample|TeachMeSalesforce

visualforcepageandapexclass.Salesforceprovidespowerfultoolslikeworkflows,approvals,validationetc.fromwhichwecan
implementourbusinessfunctionalitieswithjustbuttonclicks.
NowIwashavingarequirementwhereIneedtocreatemanyvisualforcepages,somearecustomandsomearecloningnativepage
withnativelayoutswithsomesmallchanges.Thisjustclickedmetocreateatoolfromwhichwecancreateavisualforcepagecode
withjustclickingbuttons.Yes!!Visualforcepagecodewithbuttonclick.
Thissavedalotoftime,asIdonotneedtowriteanythingtocreateaheavyvisualforcepageandamazinglyitisdonejustusing
buttonclicks.
Installthepackage:https://login.salesforce.com/packaging/installPackage.apexp?p0=04t90000000Pqos
Justappend/apex/vfgenerator__codegeneratorinURL.
NowletmejumpintotheexplanationwhatexactlyIhavedone.AsimpleUIwillbedisplayed,whereusercanselectthedesiredtype
ofpage,objectname,recordtype,emailfield.

ObjectName:ValidobjectAPIname(includenamespaceifany)
RecordType:RecordtypeIdofobjectselectedinObjectName
TypeofPage:
1.Edit:Codewillbegeneratedfortheeditpageoftheobject(accordingtorecordtypelayoutifselectedany).
2.Detail:Codewillbegeneratedforthedetailpageoftheobject(accordingtorecordtypelayoutifselectedany)
3.CustomDetail:CodewillbegeneratedfordetailpageaccordingtothefieldsselectedfromUI
4.CustomEdit:CodewillbegeneratedforeditpageaccordingtothefieldsselectedfromUI
IntheabovescreenIhaveselectedEditasthetypeofpageandAccountinobject,alsoprovidedmyemail.WhenIclick
GenerateCodeitdisplayslikethis:

Justcopythecodeandpasteitinnewvisualforcepage.WhyIhavegivenmyemailidbecausewhenyoupastethecodein
visualforcepageitwillloosealltheformattingandwilldisplayinonesingleline,butcodesentonemailwillcomewithformatting.
Sowecancopythegeneratedcodefromemailalso.Nowwhenyouhitthenewlycreatedvisualforcepageitwilldisplayallfieldsin
editmodewhicharedisplayedonnativeeditpage.Isntthatgood?
Nowletstrycreatingsomecustomvisualforcepage.SelectCustomEditinTypeofPageandAccountinObjectName.It
willdisplayasectionSelectFields.ClickonDisplayFields,itwilldisplayallfieldswhichareupdatablebypresentuser.

https://teachmesalesforce.wordpress.com/category/codesample/

7/13

3/4/2016

CodeSample|TeachMeSalesforce

SelectsomefieldsandclickonGenerateCode.Againcopypastethecodeinyourvisualforcepage,itwilldisplayselectedfields
ineditmode.
Nowheavyvisualforcepagesarecreatedwithjustbuttonclicks.
PackageprovidedismanagedbecausethetoolisundertestingandIwouldliketohavefeedbackfromyouall.Onceitisfreefromall
bugsIwillprovidethecode.
Declaration:YoumayfindsimilarpostrelatedtoVisualforceCodeGenerator.Theendresultmaybesimilarbutthereisa
considerabledifferenceintheapproachesbeingfollowedhere.SoI,herebydeclarethatmyprojectisentirelymyowncreationand
hasnotbeencopiedfromanyotherperson/organizationswordsoridea.Pleasefeelfreetodropmeanemailat
arora.salesforce@gmail.comifthereisanydisagreement.
Cheers
WrittenbyAnkitArora(forceguru)
June15,2011at2:32pm
PostedinAdvanced,Apex,CodeSample,Intermediate,Visualforce
TaggedwithCode,Generator,SendEmail

HowSalesforce18DigitIdIsCalculated
with6comments
AsweknowthateachrecordIdrepresentsauniquerecordwithinanorganization.TherearetwoversionsofeveryrecordIdin
salesforce:
15digitcasesensitiveversionwhichisreferencedintheUI
18digitcaseinsensitiveversionwhichisreferencedthroughtheAPI
Thelast3digitsofthe18digitIdisachecksumofthecapitalizationofthefirst15characters,thisIdlengthwascreatedasa
workaroundtolegacysystemwhichwerenotcompatiblewithcasesensitiveIds.TheAPIwillacceptthe15digitIdasinputbutwill
alwaysreturnthe18digitId.
Nowhowwecancalculatethe18digitIdfrom15digitId???Justcopypastethebelowcodeinsystemlogsandpassyour15digitid
inStringid
//Your15DigitId
Stringid='00570000001ZwTi';
stringsuffix='';
integerflags;
for(integeri=0;i<3;i++)
{

flags=0;

for(integerj=0;j<5;j++)

stringc=id.substring(i*5+j,i*5+j+1);

//Onlyaddtoflagsifcisanuppercaseletter:

if(c.toUpperCase().equals(c)&&c>='A'&&c<='Z')

flags=flags+(1<<j);

}
https://teachmesalesforce.wordpress.com/category/codesample/

8/13

3/4/2016

CodeSample|TeachMeSalesforce

}
if(flags<=25)
{

suffix=suffix+'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.substring(flags,flags+1);
}
else
{

suffix=suffix+'012345'.substring(flags25,flags24);
}

//18DigitIdwithchecksum
System.debug(':::::::'+id+suffix);

Thisdebugwillreturnthe18digitId.
ThisisacrossposttomyBlog
WrittenbyAnkitArora(forceguru)
June6,2011at3:47pm
PostedinApex,Beginner,CodeSample

Sendingmorethan10EmailsfromApex
with5comments
Mostoftimewestuckwithlimitswhichsalesforce.compulloverus.Ifoundthisinterestingasthispushmetoexploremorehowwe
canovercomethis.
NowwehavealimitofusingsendEmailinapexanditis10times.Isntthisbad??
ThisisacrossposttomyBlog.
NowwhenIamdealingwithanythinginbulkfirstthingcomestomymindisBatchClass.Nowwhatisthescenariowhichleadsme
tosendmorethan10emails??Ihave15systemadministratorsinmyorganizationandeachlogs23casesinaday.NowIwantto
sendanemailwhichcontainsdetailsofcaseloggedbyeachsystemadministratorseparately,meansToaddressandBodyofeach
emailwillbedifferent.
Sojustcreateabatchclasswiththiscode:
globalclassBatch_CaseEmailimplementsDatabase.Batchable<sObject>,Database.Stateful
{
Map<Id,List<Case>>userCaseMap{get;set;}
List<Case>allCaseLoggedToday{get;set;}
globalBatch_CaseEmail()
{
//Maptomaintainuseridandcasesloggedbythemtoday
userCaseMap=newMap<Id,List<Case>>();
//Allsalesrep(Systemadmins)
List<User>salesRep=newList<User>();
salesRep=[selectid,name,Email,ManagerIdfromUser
whereProfile.Name='SystemAdministrator'];
//Allsalesrepids
List<Id>salesIds=newList<Id>();
for(Userur:salesRep)
{
salesIds.add(ur.Id);
}
//Allcasesloggedtodaybysalesrep
allCaseLoggedToday=newList<Case>();
allCaseLoggedToday=[selectId,CaseNumber,CreatedById,Owner.name
,account.Name,contact.namefromCase
whereCreatedDate=TODAYANDCreatedByIdin:salesIds];
}

https://teachmesalesforce.wordpress.com/category/codesample/

9/13

3/4/2016

CodeSample|TeachMeSalesforce

globalDatabase.QueryLocatorstart(Database.BatchableContextBC)
{
//Creatingmapofuseridwithcasesloggedtodaybythem
for(Casec:allCaseLoggedToday)
{
if(userCaseMap.containsKey(c.CreatedById))
{
//Fetchthelistofcaseandaddthenewcaseinit
List<Case>tempList=userCaseMap.get(c.CreatedById);
tempList.add(c);
//Puttingtherefreshedcaselistinmap
userCaseMap.put(c.CreatedById,tempList);
}
else
{
//Creatingalistofcaseandouttingitinmap
userCaseMap.put(c.CreatedById,newList<Case>{c});
}
}
//Batchonallsystemadmins(salesrep)
Stringquery='selectid,name,EmailfromUser
whereProfile.Name=\'SystemAdministrator\'';
returnDatabase.getQueryLocator(query);
}
globalvoidexecute(Database.BatchableContextBC,List<sObject>scope)
{
for(Sobjects:scope)
{
//TypecastsObjectinuserobject
Userur=(User)s;
//Ifsystemadminhasloggedanycasetodaythenonlymailwillbesent
if(userCaseMap.containsKey(ur.Id))
{
//Fetchingallcasesloggedbysysadmin
List<Case>allCasesOfSalesRep=userCaseMap.get(ur.Id);
Stringbody='';
//Creatingtabularformatforthecasedetails
body=BodyFormat(allCasesOfSalesRep);
//SendingMail
Messaging.SingleEmailMessagemail=newMessaging.SingleEmailMessage();
//Settinguseremailintoaddress
String[]toAddresses=newString[]{ur.Email};
//AssigntheaddressesfortheToandCCliststothemailobject
mail.setToAddresses(toAddresses);
//Emailsubjecttobechanged
mail.setSubject('NewCaseLogged');
//Bodyofemail
mail.setHtmlBody('Hi'+ur.Name+',
DetailsofCasesloggedtodayisasfollows:
'+body+'
Thanks');
//Sendingtheemail
Messaging.sendEmail(newMessaging.SingleEmailMessage[]{mail});
}
}
}
publicStringBodyFormat(List<Case>lst)
{
Stringstr='';
for(Casecs:lst)
{
str+='<tr><td>'+cs.CaseNumber+'</td>'+'<td>'+cs.Owner.Name
+'</td>'+'<td>'+cs.Account.Name+'</td>'
+'<td>'+cs.Contact.Name+'</td>'+'</tr>';
https://teachmesalesforce.wordpress.com/category/codesample/

10/13

3/4/2016

CodeSample|TeachMeSalesforce

+'<td>'+cs.Contact.Name+'</td>'+'</tr>';
}
str=str.replace('null','');
StringfinalStr='';
finalStr='<tableborder="1"><td>CaseNumber</td><td>Owner</td>
<td>Account</td><td>Contact</td>'+str+'</table>';
returnfinalStr;
}
globalvoidfinish(Database.BatchableContextBC)
{
}
}

Codeisselfexplanatory,hopetherewillbenoissuesunderstandingit.
Executethisclassusingbelowscriptinsystemlogs:
Batch_CaseEmailcontroller=newBatch_CaseEmail();
IntegerbatchSize=1;
database.executebatch(controller,batchSize);

Allsystemadministratorswillgetanemailsomethinglikethis:

WrittenbyAnkitArora(forceguru)
June5,2011at2:12pm
PostedinAdvanced,Apex,CodeSample
TaggedwithBatchClass,GovernorLimits,SalesforceBatchApex,SendingEmails
OlderEntries

RecentPosts
SimplestApexTriggerPatterns
ApexHomeworkAssignment1:ControlFlowIfStatementsandForLoops
ApexHomeworkAssignment0:CollectionsLists,SetsandMaps
UnitTests:NotJustforDevIdea1
UnitTests:NotJustforDevIdea0

Search
Search

Categories
Advanced(7)
Apex(17)
ApprovalProcess(1)
Beginner(10)
CloudSpokes(1)
CodeSample(10)
Configuration(7)
Google(1)
Intermediate(9)
REST(1)
https://teachmesalesforce.wordpress.com/category/codesample/

11/13

3/4/2016

CodeSample|TeachMeSalesforce

Trigger(6)
Uncategorized(6)
Validation(1)
Visualforce(5)
Workflow(1)

Contributors

Pages
About
PostingGuidelines

Blogroll
AppirioTechBlog
CloudSpokesBlog
JeffDouglas'Blog

Stayintouch
FollowonLinkedin
FollowonTwitter
LikeonFacebook

EmailSubscription
Enteryouremailaddresstosubscribetothisblogandreceivenotificationsofnewpostsbyemail.
Join254otherfollowers
Enteryouremailaddress
Signmeup!

Meta
Register
Login
https://teachmesalesforce.wordpress.com/category/codesample/

12/13

You might also like