3/4/2016
CodeSample|TeachMeSalesforce
TeachMeSalesforce
[Link]
ArchivefortheCodeSampleCategory
SimplestApexTriggerPatterns
leaveacomment
BecausesometimesyoujustwanttoseethebasicprogrammingpatternsforApexandreverseengineerthemtofityourneeds.
[Link]:setafieldsvalueonarecordwhenthatrecordisadded
[Link],notonupdatebecausethatsslightlylesssimple(andadifferentpost).Theonlydifferenceis
[Link]?[Link]
ortheotherbuttodaywejustwantcodethatworks,sohereyougo:
TriggerContactBeforeTriggeronContact(beforeinsert){
for(Contactc:[Link]){
[Link]=true;
}
}
TriggerContactAfterTriggeronContact(afterinsert){
ListconList=newList();
for(ContactconInTrigger:[Link]){
Contactc=newContact(Id=[Link],HasOptedOutOfEmail=true);
[Link](c);
}
updateconList;
}
AndofcourseanythingyouwanttouseinProductionneedsatestclass,sohereyougo,onethatworksforboth!
@isTest
publicClassTestContactTrigger{
publicstatictestMethodvoidtestContactInsert(){
ContactaNewContact=newContact(LastName='qwerty');
InsertaNewContact;
ContacttheInsertedContact=[SelectHasOptedOutOfEmailfromContactlimit1];
[Link]([Link]);
}
}
WrittenbyAlwaysThinkin
February28,2016at4:53pm
PostedinApex,Beginner,CodeSample,Trigger,Uncategorized
UnitTests:NotJustforDevIdea1
leaveacomment
Unittestsoffermuchmorethanjustthemeanstoget75%+codecoverage,andtheycanbeusedtoprotectmorethanjustApex.
ReadtheintrotothisseriesinIdea0.
Ourfirstexampleisthesimplest:[Link]
[Link]
1/13
3/4/2016
CodeSample|TeachMeSalesforce
[Link],[Link]
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@[Link]
nothingyoudointheClasswillbesavedtotheserver,[Link]
usemostrecordsthatexistontheserver,soyouhavetocreateyourowntestrecords.
@isTestmeansthatSalesforcewillrecognizeitasatestClass,andwhenyouRunAllTests,itwillknowtorunthistesttoo.
NextistheClassName,[Link],privateis
thedefault.
TheactualtestMethodhereisprotectFields().Yourtestexistsbetweenthecurlybraces{}.Hereyoumustcreateyourtestrecords
[Link]
[Link],Salesforcewillnotreportatestfailureregardlessoftheoutcome.
[Link],topopulatefieldsonthatLead,andfinallyto
[Link],sobesuretoinclude
anyfieldsaffectedbythem.
OncethisUnitTestissavedtotheserver,anyattempttodeletethefieldorchangeitsdatatypewillbeblockedwithareferenceto
thisUnitTest.
Forthislimitedscenario,thatsallweneed!
WrittenbyAlwaysThinkin
August3,2014at3:53pm
PostedinApex,CodeSample,Intermediate
TaggedwithApex,UnitTest
SalesforceTriggerwhenRollupsSummariesNotPossible
with6comments
[Link],itsnotpossibletoimplementa
[Link]
codeforeachclassisavailableatGitHubforyourforkingpleasure.
Soheresthe(notveryuseful)[Link](detailobject).
[Link]
updated,iftheSalesOrderItemismarkedasprimarythenthevalueofpurchasedcountryiswrittenintotheprimarycountry
[Link]
[Link]
[Link].
[Link]
2/13
3/4/2016
CodeSample|TeachMeSalesforce
[Link]
[Link],triggersshoulddelegate
[Link].
SalesOrderItemTrigger(sourceonGitHub)[Link]
SalesOrderItemTriggerHandler.
triggerSalesOrderItemTriggeronSales_Order_Item__c(afterinsert,afterupdate){
SalesOrderItemTriggerHandlerhandler=newSalesOrderItemTriggerHandler();
if([Link]&&[Link]){
[Link]([Link]);
}elseif([Link]&&[Link]){
[Link]([Link],[Link],[Link],[Link]);
}
}
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)
[Link](soi.Sales_Order__c,soi.Purchased_Country__c);
}
[Link]
3/13
3/4/2016
CodeSample|TeachMeSalesforce
//queryforthesaleordersinthecontexttoupdate
Listorders=[selectid,Primary_Country__cfromSales_Order__c
whereidIN:[Link]()];
//[Link]
//usingthesalesorder'sidasthekey
for(Sales_Order__cso:orders)
so.Primary_Country__c=[Link]([Link]);
//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@[Link]');
insertc;
so1=newSales_Order__c(name='test1',Delivery_Name__c=[Link]);
so2=newSales_Order__c(name='test2',Delivery_Name__c=[Link]);
insertnewList{so1,so2};
}
statictestMethodvoidtestNewRecords(){
Sales_Order_Item__csoi1=newSales_Order_Item__c();
soi1.Sales_Order__c=[Link];
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=[Link];
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=[Link];
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=[Link];
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=[Link];
soi5.Quantity__c=1;
soi5.Description__c='test';
soi5.Purchased_Country__c='Italy';
insertnewList{soi1,soi2,soi3,soi4,soi5};
[Link](2,[selectcount()fromSales_Order_Item__cwhereSales_Order__c=:[Link]]);
[Link]
4/13
3/4/2016
CodeSample|TeachMeSalesforce
[Link](3,[selectcount()fromSales_Order_Item__cwhereSales_Order__c=:[Link]]);
[Link]('France',[selectprimary_country__cfromSales_Order__cwhereid=:[Link]].primary_country__c);
[Link]('Germany',[selectprimary_country__cfromSales_Order__cwhereid=:[Link]].primary_country__c);
statictestMethodvoidtestUpdatedRecords(){
Sales_Order_Item__csoi1=newSales_Order_Item__c();
soi1.Sales_Order__c=[Link];
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=[Link];
soi2.Quantity__c=1;
soi2.Description__c='test';
soi2.Purchased_Country__c='France';
soi2.Primary_Item__c=true;
insertnewList{soi1,soi2};
//assertthatthecountry=France
[Link]('France',[selectprimary_country__cfromSales_Order__cwhereid=:[Link]].primary_country__c);
Listitems=[selectid,purchased_country__cfromSales_Order_Item__c
whereSales_Order__c=:so1.idandprimary_item__c=true];
//[Link]
[Link](0).purchased_country__c='Denmark';
updateitems;
//assertthatthecountrywassuccessfullychangedtoDenmark
[Link]('Denmark',[selectprimary_country__cfromSales_Order__cwhereid=:[Link]].primary_country__c);
WrittenbyJeffDouglas
August23,2011at9:00am
PostedinApex,CodeSample,Trigger
JavaScriptRemoting
with2comments
Oneofthemajorenhancementsfromvisualforcethisrelease(Summer11)andmyfavoriteisJavaScriptremoting.
[Link]
isnowavailableaftersummer11release.
Hereisaquickexample:wehaveaApexclasswhichdefinesagetAccountmethod.
globalwithsharingclassMyJSRemoting
{
publicstaticAccountaccount{get;set;}
@RemoteAction
globalstaticAccountgetAccount(StringaccountName){
account=[selectid,name,phone,type,numberofemployeesfrom
Accountwherename=:accountNamelimit1];
returnaccount;
}
}
Thismethodishaving@[Link]
pagewehaveascripttagsetwhichishowweembedjavascriptwithinvisualforcepages.
<apex:pagecontroller="MyJSRemoting">
[Link]
5/13
3/4/2016
CodeSample|TeachMeSalesforce
<scripttype="text/javascript">
functiongetAccountJS(){
varaccountNameJS=[Link]('accountname').value;
[Link](accountNameJS,function(result,event)
{
if([Link])
{
[Link]("{!$[Link]}")
.innerHTML=[Link];
[Link]("{!$[Link]}")
.innerHTML=[Link];
}
},{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.
[Link].
JavaScriptRemotingisthefeaturewhichisprimarilybeusedbydevelopersandwillallowthemtocreatericherandmoreinteractive
userinterfacesthateveryonewillbenefitfrom.
Inparticular,letsdeveloperscreaterichjavascriptbaseduserinterfacesbyinvokingapexcontrollermethodswithinJavaScriptcode.
[Link]
atypicalvisualforcereRendermodel,[Link]
[Link].
AdditionalVisualforceenhancements:
1)FilteredLookupviaVisualforce.
2)Inlineeditingforrichtextareafield.
3)FieldSetpropertyaccessors.
ThisisacrossposttomyBlog.
WrittenbyAnkitArora(forceguru)
June19,2011at4:33pm
PostedinAdvanced,Apex,CodeSample,Visualforce
VisualforceCodeGenerator
with9comments
ThisisacrosspostfrommyBlogPost.
[Link]
[Link]
6/13
3/4/2016
CodeSample|TeachMeSalesforce
[Link],approvals,[Link]
implementourbusinessfunctionalitieswithjustbuttonclicks.
NowIwashavingarequirementwhereIneedtocreatemanyvisualforcepages,somearecustomandsomearecloningnativepage
[Link]
[Link]!!Visualforcepagecodewithbuttonclick.
Thissavedalotoftime,asIdonotneedtowriteanythingtocreateaheavyvisualforcepageandamazinglyitisdonejustusing
buttonclicks.
Installthepackage:[Link]
Justappend/apex/vfgenerator__codegeneratorinURL.
[Link],whereusercanselectthedesiredtype
ofpage,objectname,recordtype,emailfield.
ObjectName:ValidobjectAPIname(includenamespaceifany)
RecordType:RecordtypeIdofobjectselectedinObjectName
TypeofPage:
[Link]:Codewillbegeneratedfortheeditpageoftheobject(accordingtorecordtypelayoutifselectedany).
[Link]:Codewillbegeneratedforthedetailpageoftheobject(accordingtorecordtypelayoutifselectedany)
[Link]:CodewillbegeneratedfordetailpageaccordingtothefieldsselectedfromUI
[Link]:CodewillbegeneratedforeditpageaccordingtothefieldsselectedfromUI
IntheabovescreenIhaveselectedEditasthetypeofpageandAccountinobject,[Link]
GenerateCodeitdisplayslikethis:
[Link]
visualforcepageitwillloosealltheformattingandwilldisplayinonesingleline,butcodesentonemailwillcomewithformatting.
[Link]
[Link]?
[Link]
[Link],itwilldisplayallfieldswhichareupdatablebypresentuser.
[Link]
7/13
3/4/2016
CodeSample|TeachMeSalesforce
[Link],itwilldisplayselectedfields
ineditmode.
Nowheavyvisualforcepagesarecreatedwithjustbuttonclicks.
[Link]
bugsIwillprovidethecode.
Declaration:[Link]
[Link],herebydeclarethatmyprojectisentirelymyowncreationand
hasnotbeencopiedfromanyotherperson/[Link]
[Link]@[Link].
Cheers
WrittenbyAnkitArora(forceguru)
June15,2011at2:32pm
PostedinAdvanced,Apex,CodeSample,Intermediate,Visualforce
TaggedwithCode,Generator,SendEmail
HowSalesforce18DigitIdIsCalculated
with6comments
[Link]
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=[Link](i*5+j,i*5+j+1);
//Onlyaddtoflagsifcisanuppercaseletter:
if([Link]().equals(c)&&c>='A'&&c<='Z')
flags=flags+(1<<j);
}
[Link]
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
[Link](':::::::'+id+suffix);
Thisdebugwillreturnthe18digitId.
ThisisacrossposttomyBlog
WrittenbyAnkitArora(forceguru)
June6,2011at3:47pm
PostedinApex,Beginner,CodeSample
Sendingmorethan10EmailsfromApex
with5comments
[Link]
canovercomethis.
[Link]??
ThisisacrossposttomyBlog.
[Link]
tosendmorethan10emails??[Link]
sendanemailwhichcontainsdetailsofcaseloggedbyeachsystemadministratorseparately,meansToaddressandBodyofeach
emailwillbedifferent.
Sojustcreateabatchclasswiththiscode:
globalclassBatch_CaseEmailimplementsDatabase.Batchable<sObject>,[Link]
{
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
[Link]='SystemAdministrator'];
//Allsalesrepids
List<Id>salesIds=newList<Id>();
for(Userur:salesRep)
{
[Link]([Link]);
}
//Allcasesloggedtodaybysalesrep
allCaseLoggedToday=newList<Case>();
allCaseLoggedToday=[selectId,CaseNumber,CreatedById,[Link]
,[Link],[Link]
whereCreatedDate=TODAYANDCreatedByIdin:salesIds];
}
[Link]
9/13
3/4/2016
CodeSample|TeachMeSalesforce
[Link]([Link])
{
//Creatingmapofuseridwithcasesloggedtodaybythem
for(Casec:allCaseLoggedToday)
{
if([Link]([Link]))
{
//Fetchthelistofcaseandaddthenewcaseinit
List<Case>tempList=[Link]([Link]);
[Link](c);
//Puttingtherefreshedcaselistinmap
[Link]([Link],tempList);
}
else
{
//Creatingalistofcaseandouttingitinmap
[Link]([Link],newList<Case>{c});
}
}
//Batchonallsystemadmins(salesrep)
Stringquery='selectid,name,EmailfromUser
[Link]=\'SystemAdministrator\'';
[Link](query);
}
globalvoidexecute([Link],List<sObject>scope)
{
for(Sobjects:scope)
{
//TypecastsObjectinuserobject
Userur=(User)s;
//Ifsystemadminhasloggedanycasetodaythenonlymailwillbesent
if([Link]([Link]))
{
//Fetchingallcasesloggedbysysadmin
List<Case>allCasesOfSalesRep=[Link]([Link]);
Stringbody='';
//Creatingtabularformatforthecasedetails
body=BodyFormat(allCasesOfSalesRep);
//SendingMail
[Link]=[Link]();
//Settinguseremailintoaddress
String[]toAddresses=newString[]{[Link]};
//AssigntheaddressesfortheToandCCliststothemailobject
[Link](toAddresses);
//Emailsubjecttobechanged
[Link]('NewCaseLogged');
//Bodyofemail
[Link]('Hi'+[Link]+',
DetailsofCasesloggedtodayisasfollows:
'+body+'
Thanks');
//Sendingtheemail
[Link]([Link][]{mail});
}
}
}
publicStringBodyFormat(List<Case>lst)
{
Stringstr='';
for(Casecs:lst)
{
str+='<tr><td>'+[Link]+'</td>'+'<td>'+[Link]
+'</td>'+'<td>'+[Link]+'</td>'
+'<td>'+[Link]+'</td>'+'</tr>';
[Link]
10/13
3/4/2016
CodeSample|TeachMeSalesforce
+'<td>'+[Link]+'</td>'+'</tr>';
}
str=[Link]('null','');
StringfinalStr='';
finalStr='<tableborder="1"><td>CaseNumber</td><td>Owner</td>
<td>Account</td><td>Contact</td>'+str+'</table>';
returnfinalStr;
}
globalvoidfinish([Link])
{
}
}
Codeisselfexplanatory,hopetherewillbenoissuesunderstandingit.
Executethisclassusingbelowscriptinsystemlogs:
Batch_CaseEmailcontroller=newBatch_CaseEmail();
IntegerbatchSize=1;
[Link](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)
[Link]
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
[Link]
12/13