You are on page 1of 512
By BENED SOFTWARE rce No 1 Training Institute for Salesforce.com in India Development Material (Apex, VisualForce, Deployments) Completed 150+ Batches 300+ Students Placed 500+ Students Certified 13 Corporate Trainings in MNC's 80+ Workshops on integrations & Webservices *** 3 Months Internship in MNC's*** on Salesforce.com Trainer: Satish Myla New Bathes & Workshops starts on every Saturday Contact for Demo: +91-7799458889 Bened Software (P) Ltd, €-3-219/1, 4th Flog, OTDC Opp Building, Near Saradhi Studio, Ameerpet-38. Ph: 040-66781355/56 &1 w.benedsoft.com 5 BENED SOFTWARE Drive for Exe INDEX S.NO TOPIC NAME PAGE NO 1, When Should | Use Apex 1 2. How Does Apex Work 2 Object Oriented Programming (Oops) 3. Data Types 3 4. Class 5 5. Access Modifiers 6 6. Class Variables s 7. Object 9 8. Constructors 10 9, Usage of Apex Program With in VF Page i 10. Reffering to the Apex Class In VF Page 12 11, Example for Getter Method 13 12. Apex Class to Demonstrate Setter Method 14 13. Call Apex Methods in A VF Page 15 14, Simple Apex Class 16 15. Array 17 Bened Software (P) Lid, 8-3-219/1, 4" Floor, DTDC Opp Building, Near Saradh! Studio, Ameerpet Ph:+91-40-66781355/56, traming@benedsoft.com www.benedsoft.com BENED SOFTWARE prive fo 16. Pick List Using Select Option from Apex 18 17. Collection © List 20 * Set 24 © Map 27 18. SOQL Queries 32 19. Child to Parent Relationship On Standard, Custom Objects 40 20. Example Program 4 21. Parent to Child Relationship On Standard, Custom Objects 43 22.SOSL Queries 46 23, Email Programming 49 * Outbound Email Service 50 * PDF File Attachment 34 © Inbound Email Service 58 24, DML Operations 62 25. Interface Iterator 67 26. Interface Iterable 70 27. Database.QueryLocator Class Ps 28. Batch Apex 73 © Start Method ¢ Execute Method ¢ Finish Method Bened Software (P) Ltd, 8-3-219/1, 4" Floor, OTDC Opp Building, Near Saradhi Studio, Ameerpet. Ph:+91-40-66781355/56, training@benedsoft.com www.benedsoft.com BB BENED SOFTWARE Brive for &: 29. Invoking Of Batch Apex Job 30. Order Of Execution Of Batch Apex Jab 78 31. Database. Stateful 81 32. Governing Limits,Limitations 83 33. Apex Scheduler 84 34, Real Time use cases for Batch, Schedule Apex 89 34. Testing 100 35. Batch Apex Example With Test Case 106 36. Schedule Apex Example With Test Case 107 37. Triggers & Examples 109 38. Invokong Apex methods in Triggers 124 39.Recursive Triggers 40. Order of Execution Of Triggers 131 41. Future Annotation 139 42, Apex Sharing Rules 142 43. Flows Introuduction 146 © Process.Plugin Interface ‘© Input parameters Output Parameters 44, Plug in Program 150 45. Select Option 154 46. Schema Programming 156 47. JSON(JavaScript Object Notation) 167 48. http Callouts 180 49. JQUERY 183 Bened Software (P) Ltd, 8-3-219/1, 4" Floor, DTDC Opp Building, Near Saradhi Studio, Ameerpet. Ph:-+91-40-66781355/S6, training@benedsoft.com www.benedsoft.com 5 BENED ow Exe 50. Introduction to VisualForce Page 51. Apex Components mn © Apex Page © Formula & Expressions in VF © Apex PageBlock Formula Expressions © PageBlock Section ¢ PageBlock Buttons ¢ Command Button ¢ Command Link © PageBlock Section Item Apexlnput Components Input Text Input Secret «Input Hidden © Input Checkbox © Input Text Area # Select List Select Option * Select Options © Select Radio © Input Field * Select CheckBox 53. Java Script in VF Page * Introduction to Java Script © Arrays in Java Script © Methods in Java Script © Reading Sobject data in Java Seript sale pre. 1 189 190 197 205 © Reading VF input component data in Java Script © Validations in Java Script 54. Page Block Table 217 Bened Software (P) Ltd, 8-3-219/1, 4! Floor, OTDC Opp Building, Near Saradhi Studio, Ameerpet. Ph:+91-40-66781355/56, tre com, www.benedsoft.com, JB BENED SOFTWARE Drive for Exeilence 55. Data Table 56. Data List 57.Apex Tab 58. Insert & Include 59. VF Page in PDF Format 60. Action function, Action Region, Action Support 61. Real Time Scenarios 62. Reports & Dashboards in VF 63. Google Maps in Salesforce 64. CSS 65, Remote Method invocation Java Script 6. deployments . ey Eclipse * Us ny Change at et Tnteqrations salesfOroe 3m 223 224 226 229 238 240 249 256 261 270 NOfE t= You can collect Toteqaotions & kebsesuicog avd book C65 Pager) B nook beok of 20 pages toon Front Dee. TS Cues all intequations Croumples (sip -STEBEL ,Not Suite; Tava. net (Tea & vrany ‘Trwke), Bened Software (P) Ltd, 8-3-219/1, 4" Floor, DTDC Opp Building, Near Saradhi Studio, Ameerpet Ph:+91-40-66781355/56, trainina@benedsoft.com www.benedsoft.com Ee BENED SOFTWARE alegfSrce.cor in 2 Days Workshop Batch Starts Salesforce Integra‘ on every Saturday 1. Introduction to API's > Meta Data API SOAP API REST API Chatter API Bulk API ‘Streaming API vvvvY 2. Meta Data API > introduction Meta Data API Advanced Programs > Deployments into different org’s. 3. Introduction to Web Services > Difference between Http 1.0 and Http 2.0 Introduction to SOAP API Types of WSDL files and their purposes Creating Web Service classes in SFDC Consuming external WSDL file in Salesforce Salesforce to Salesforce integration using Enterprise WSDL Salesforce to Salesforce intergration using Partner WSDL Salesforce to Salesforce Integration using Apex WSDL Consuming Salesforce resource in java using Enterprise WSDL Consuming Salesforce resource in java using Partner WSDL Callouts using SOAP services from Apex Chatter Example using SOAP AP{ Vv vVvvVvVY viv 4. Introduction to HTTP > 1HttpRequest 2.HttpResponse > 3.JSON Parsing > 4.XML Parsing S 5. Introduction to Rest API > Creating a Rest methods in Salesforce » Consuming Salesforce Rest Resource in Salesforce > Introduction Authorization ‘ened Software (P) Ltd, 8-3-219/1, ath Floor, DTDC Opp Building, Near Saradhi Studio, Ameerpet-38. Ph: 040-66781355/56 training@benedsoft.com www.benedsoft.com gz BENED pains for Exellence Authorization using 5 API keys YouTube Integration with Salesforce using API Key Face book integration using Salesforce Difference between OAuth 1.0 and OAuth 2.0 Authorization using the OAuth2.0 Web Server Authorization using the OAuth2.0 User-Agent Authorization using the OAuth2.0 Username Password Authorization using the OAuth2.0 refresh token Calling Third-Party services using HTTP Callouts( Two examples) VvVYVYVvVY | Google Maps and Google API's using HTTP callouts and using JavaScript Single Sign On Integration using OKTA Marketo Integration with salesforce 9. OnDemand integration with salesforce 10. Salesforce.com sites integration as Twitter/Facebook 11. Informatica Integration using Rest API 12. CAST IRON Integration 13. Outbound Messages 14. Chatter API > Introduction to Chatter API > Advanced program Oxo 15, JIRA CRM and Net suite CRM integrations Formats Many More to .. Bened Software (P) Ltd, 8-3-219/1, ath Floor, DTDC Opp Building, Near Saradhi Studio, Ameerpet-38. Ph: 040-66781355/56 training@benedsoft,com www.benedsoft.com JB BENED SOFTWARE fp - Drive for Exel Lene Interview Questions Every Bened Student can answer these questions 1) Visualforce Basic Questions 1. What is view state in visual force? 2. Which api used to design visual force page? 3. What is the difference between actionSupport and actionFunction 4, What is the actionRegion? 5. What is difference between insert and include? 6. 7. 8 9 . How do you use static resource in VF page’ What is remote action? How many records we can print a pageBlock What is the difference between related List enhanced List ,detail 10. What is the difference between controller and extension? 11. What is Ajax? Have you used it?if so tell the scenario ? 12. What is Jquery ? Where you have used? 13, What is S-Controls? 14, What is the use Static Resource in Visual force? 15. Can I pass parameters from VF page to apex method? 16. How do you refer to current page id 17. Tell me something $Action 18. How do you embed Google map in visual force? 19. How do you pass the parameters from page to page ? 20, What are custom components? 21. How do you make a VF pag: lable for Salesforce! 2) Apex fundamentals waene Bened Software (P) Ltd, 8: What is Apex? What API is used in the apex? What are the access modifiers in the apex? Whaat is the difference between With Sharing and Without Sharing? What is a constructor? What is the use of the static variables? 219/1, 4” Floor, DTDC Opp bulding, Near Saradhi Studio, Ameerpet, Hyd-38. Ph: +91-40-66781355/56 training@benedsoft.com, www. benedsoft.com gg BENED SOFTWARE salegfonce om Drive for Exellence 7. What are reference variables in apex? 8. What are Sobjects? 9, What is the difference between List and Set? 10, What is Map in apex? 11. Can we have duplicate Keys in Map 12, How many objects we can store in list? 13, What are setter and getter methods? 14, How do you refer to current page id in apex”? 15, How to do you invoke standard actions in apex class? 16, What is page reference? 17. How do you pass the parameters from om apex class to another to another? 18. What is virtual class? 19, What is interface? 20, What is abstract class? 21, What is overloadin; 22. What is overriding, 23. When we invoke with sharing method in without sharing class Now method is Executed as? 24, Will the inner class inherits the sharing properties of outer class? 25. Base class is declared as With Sharing and Derived class is declared as without Sharing what will happen? 26. Can I have constructor with parameters in apex? 27. Dereferncing a Null pointer value error? 28. Variable is not available? 29. Too many Records: 10001 3) Batch Apex and Schedule apex questions. What are the Soql limitations in apex? What are transaction limits in apex? What is the need of batch apex? ‘What is Database.Batchable interface? Define the methods in Batchable interface? ‘What is purpose of Start method in batch apex? What is the Database. QueryLocator? What is the Iterable. Cops fundarnentale 3. Doda. types 10 Apex. 4 Aecoss Modifiers S. Methodls . 6. Apex. classes JL. Obieck Cmation &, Consteactors 9, Grektus & setters matheds lo. calling Apex Mmembeas iy visualfoxo Ip. Uisualfeea with Apex Examples on Apex. ® Al Apex ig a Strongly typed object osiemtad proysamming languoge: —> Ut allows the developers to execute long and tvangaction Contsol Statements. —> Apex ernbles Pauclepuss to add business logic to most eystorn events lie buttery clicks velatel vecord updates ard uisualleke Pages. : — Apex far ) Sees ed 2 Ot prides built in guppost feb pac alls, 1) Inlone Galesfrica ebiect quesy language & w Eaay to use, eo 4 Y Eaay to toot. W) Vexsion ul) Multi tenant awaxe When should ¢ use Apex :- >To Greate email Sumuice, * — Conte nebsasyices, — pastor complex validation overs ‘roultiple objects, > TO create Complex. businese procesees that oxo not suppdted by Wwort flew. —> Create Custom teansaction logic. —> Attach cisterns logic to anothes opasation. { } | All Apex programs suns entively ON—darnand on Foxe: corn Platidmn. How does Apex Hick t- —> Fieet the platform application oS Comnpiles the Cede into ae absteact cet of Tnttsuctions that ain be Uirdusctood by Apoa santime intexpmtes. — > The Corapile Cede is Stowed to reetadata- > ban the ord ais tigqeas the execution of Apex by click button 8) wigualf{ece fog the application Serer netsionee tho Cornpiled insteuctions fron the ‘etadata and send thom to Sun time tesprokts below rekeroring the verult. Obiuct oriented programming Coops) — Cop (obiect ovierntect prograuremring) is a Trotherblogy that prouicles o Hoy ot vredulanising & program by cxeating fastitiond mernosy aac. $8 both dato and ‘wethecs that aad-B, ed as tormplate fo} Creating copia of Such recules Cobiécts) on darsard. Unlita. procedural Peogravmmning phase in tho COP progam veal, progams asc dyanized csvcund objects yy oo rathas than action and Lone. athe ‘rain cops principles oxo Encapsulation Intositarce Polyrresphism. Eraaptulation - “he ksvapeing cap of data cond Trethods tegethag is called oncapsulation. Fob example, if no tage aclag, We woite tho uasiables and methads Maide the class. Thus ; clase te bbireling tforn together fo Cast 18 ain example fed encapsulation, Dobesitance - H ceccrtes nen claseee fsorm exisisting Chases, so brat the new clagees will cxcgtaine tl the feature of the exisicting chases is called Inhesitance. : A qed example #3 Inloritance in natuw ic fasents perducing the childson and chibsen Tohexiting Che qucalition of tho pasents. polyrresphis ny - Polyreaphicm vepresents one for in Yraltiple Poors. Dr Propsorming ; We Cn wae A singe vowel to relay to objects af differant types ard variable We call the Yrethade of differant Call con pestorm differant taseg 1 Cbyect - Apes fundamentals s— . Dato pe = : > Dota type im the Apex ero! type of data can be tored. a > What is tho AN hat can be Sipsed. y Premnilitle da we WW) collecti r WY) Eoume \) prerntive data ‘tegpeg 1 These ase the cata types cohich axe Por defined by the Apex, —? A Prewitiue dala types Such aa an Integas ; Double Lemp Pate, Date Rina, String, 1D 8 Brokaw, QB AS —> All Prermitiua chte types o%@ fared by vole not by wferonce. > Al Apex vostables, nhathas theiy or class member Vassiables axe “witiakided © vu) Make cuse that We isitiali2e Uassiables to appsopsiode Wakies before using thom. Apox Premitive datatypes trclude = Boolean '- A, valu tot an only be cuigned tous folsench rad, Egr Boolean isActive = false; 3 Dette A value thot indicates a. paviticulas day. Datowlealuss Contain tno ‘wfosmation about time Dato Ualueg must Guuoays be created With G& Systern Static method. Xe Date Toypate = Date. reninatante (2.018 , OF) '5)) Output 1S 2012-05-15 0 100:00 Time and DateTrne these die, date types axseciated with datey and mag along with Pate cis tym. the Hane dodo. typer Stovey Limes Chowne, tivutes, Secon and yill’secords). the Dose chia types Stowes chica (eau month and day) . the Datetime Chtactype tower both dates ard Frnes Each of these clases haga teaTnstanee method pith cahich tye can Conrieet Pawticulay date and time Uoleas . Eqz Trme tt = now Tnatance (tq; 20)! 2); olp B 19:20:01 Apexi — bie can also create cate and ma som te Cusvent sutsrent clock . Dote my = Dotetime non); Pate += Date today}: —> The date and time classes alo have instance motheds 2% Conuesting fromm one format to anotinars . EQ- Tino tg Date time. Non). mac )- — > We can ako manipulste the valued by wat “vastanc. methede. EQ? Dodo 43> Dake today ©), Dette Noxt = » wie will get s Cute Q013 - ao ran Int — TO Stove Dummaic value ‘nm as \ “A doe Of the Nuyresic data types, a -f 3 Dumbay that doen't trelude a cwetwal podat: Toveguns haue A minima Value of 2, 4, 483,648 and @ wate valuo of &) 1Yt, 48s, HF Eg Totegers teh “A A A An nA a re Apex-1 i At Jong’ A o Bit “ambea that doem't include a decimal point. (orgs have a Minimum Valux of —263 avd a maximum Vales of 263-l qr dong P= AUFHBSREL, Doulle- A cip-bit rermbag that incladag a dacinml psmnt - Doubles hase a minima Value of —263 and a Tdximum vale of 263-(, Gyr Ooubl d = 2.14159" OS) Decimal — Ay rumbes that treludes a ceciypal polab: niin is an Oxbitasy Precision nuymbus . Curmency Prades axe alte ratioally Oseigned Che tym docival . C ; > Decivral dac= 19-23; d Nall variables - 20 ne ceclawe a uaa! cond con't initialiae it With o Valus t willbe null Nae yoens the absence of auoless Aue can algo asKign a vault to any vasniable doclard witha : Promitive type Both of these Stafemenic Beault & a Vasiable set tonull . Boolean y= pull Deckert a; Steing + Stoings ose setof chawactege cond ear anclosed ina Srp quetel. thay ctore text valu guchag a name San actos, Egy mb di= Mate todas ) . Staing S = Sting Valeo AD; The ofp of above exampk Should be today’s dae. 20/3-06- 6. SObieck Types — An Sobiect , can be a gpresic SObiect os be a Specific Sabjects, Such ag cn Account Contact os MYCustorn__c. > Sobjects (shoot fox “salerforee chiects") axe Ctardax & custom objects that Stoves secosd data in tho Fase Com database. these ic ako an Sobject data type iy Apex that is Negrratic Depsertntation of thee SObiects and thie > Durclopers wefes to Sobiects and APL Names. Br Account a =new fleco My Gustomobiect—C obiect -_C OY L API name of & J =) the foll ouirg are Mgt ‘an invoice Statement Nith S7e ‘mitiad CS siption__c fietde and osigns Tnwetee- Statamont——C ,»hich ® an Sobject type ee os) Qs Poyoia -Statement__¢ tv- Nus Device Statement —C Coesesiption_¢ = Great Towite'!, latus c= ‘pording’) = Sobyect Vassiables axe initialised to mulb, bu can be Asxigney a Laid Object weference with the now Operate. RRR RR RRR RRR RRA AAR et ttn Class *- os “Clase isa Collection of datamembars and ‘methede. qr class, Studant Tnteges oe axe dotamembesg a Sting rare: the charg . y Pablic void getDetails _> Thie ic the, wethed System chbug ollno | +ne); ° of the clase) System . debug (‘narre! -trarme); $ 4 Er class Employee i Integug exp; i { > Uowriableg [oedourerntonas Stang dapastmnent Of the clay , Neoid thecoc ) : —snethad of f [hasnt te je Feo” ' § — 370 dafina an Apex class Spacify the following. 1) Accare-madifians*- — You. Tout use oe Of the access Madifiens KS top (enol Clay. (public d.global) —> you do not have to wpe access Wwadifiass ‘in the declaration of Wner chasceg . & 1) optional definition rmedifiess serch io ack Ww Reqrsisucl tthe key ood (| clare rane, lu) Optional extensions | Anofe Rey it merrosy fd tho datamembess aur allocated only whan you Create a object Syntax'- a objeckname = yew clasgrame( 9: fa . “this the Tame \ i | 0" ; Tea Tis Constssct\ . of claga 1Suhon vrelmange Keeps Ge ass coca Vastable — Which cat) an object. PF allocating the oomdy dass Example \\cedo % ample Soma Example); Conctauctor +! Constoudts), iS 0 Spectall wethad Htheh howe the following Poopestiog. +) Methad name will be Sarme ag clase. if) Accessspecifiers, catll be pubic WY This vrothad cell invoked only ome thet is at the fime of Creaking an object - ivy this ig Usted to instantiate the dato. membess of the clas, Ege ~ public chug, TestObiect f \\the 0 Oxgeernent Conttocactos Public Testobject¢ > / \\ Cod 8 $ w These axe 3 types of conttructede U Default Consts 2) Non —posametexizad Ciagteu 3d preametusize TLR Y) Defasete Cretsucithe Tan ae n't Contain any constrect) then Apex 5 ult creates a. deermny Consbuctd} on the Tame Johor eee cwento On Obiect $b the clagy a) F es class Example . Example ¢ = nen Example ¢ >> SOR RR RRR Re AR Rm nen ne ne en AYO Ty tre above exampe, tha apex class dooto't Contain any Constsuctth « $0 whan we create abiect Fo\ Etaumple clas the Apex Corfilag crater adofault Constsuctds. am public excumple¢) $ me %) Non- pawcumetusised d consteuctsh % pasarneberiaed Gonstouctos + Ris cvconstucls ceo 7 any poxouniptess, OF Conetsuctd) Fat hag xCly gr public clas, Example PR \ f Trteqen, ™o Stsing Naw ie Public Exarnple integers Sing mYName) > pa.xametesized| f ‘ Corttsuctor oo = a ame = Toyrarne, & Public -Excunple () eda T0210; | — THIS 1S MOD - parcumetarized Meda vara sm | — Conttyuctox Woite a Apex program to demonstiate Usage of Gonstsuctd. 1) Open daustoper Console wade, by clicking the Nome on the Salestceo page ® dice File & select Apex clasg. 3) Entes the class rome. K) hlvite tha Apor chagg Public class employee String Ermployeo naw » A Integus, Ereployer no; . ee =a © Systero debug ( 'eroplayeename ie ‘+empogeriame), ~ System. ‘debug C'Erplepeno ue ' + Erplagenvo); RT RRR RRR Re nn nen enn AY 5) Open the anongrnous block . Employee CL= Nan Employee ©); Employee 22 = nen cate, 21 Showl >; Q2 Show (); THIS IIL Give avr output Of Employee Naame cp Hast and Employeeno is to. ~O\ Ermploycenawe ts Hani. Employeeno — te, usage of Apex peogwarn ewith within. NiSeal}de poge Ythen get cmt to tse cad Apex clagg tM Visualfedce poge be have to declase ip the Fallessing forrnad < Apex: page Contyolleey ="clyy maine" > ‘ Whenexeg, ke aa Wisualfcke page in which Conteollesy, GHtsibute 1S defined i will fixst create an obiect fA the apex clay bhich ey define in Conten(lers, QY Wham Sbiect ic crsated fos tha Apex clogs first YH invokes the Covttsuctos . \\ | | RePeeving to tho apex clay rrambese in visualteske t LAlbarn your count to refers apex clase yousiables in the wisual fake Fage toe Need to Wye Getta & Settas mothode geee) Public clas, Crarnple Stsing name; : re § get Method :- s When uisualfdxe Page want to “2 Of 0 (ousiahle datiancd mm tho Apex. 3 TAyoke get mathed of that vasiatle &e © haa core RON Pama} ge é b ‘this is 0 Vasiable dafined in apex. close. Bp the aboue rent visual fice page is taying 4o uge Tyrowe \rawiable hich ig daclased in Apex clagg $0 it is invoke autorratienlly getMynamad ) metrod in the apex car and this rethed will telus tho values of that ee ee a Ae am ha ee me public chasg Example f Sting nome 5 Public void set Coring ‘rame) £ — sattas method - this co'lll this. narme = Towne ; take tho alee Prom the & visual{aee Poge ahd) Cnneg te ne ra public Stving gebttamnec ) ye £ — Qettes mmethed this method wetusp Name; uiill vate deualue too % : \tisuall tekoa age Wheneuay q TOM 3 \Vaisiable “ig called. ais Public class Excurrgple t i Pte ero, * pablc void sek (StsimoIniegys no) § this.no =no; & Public Trkequg getNoc > Fetusy VO > 3 3 \a Waite 20 example teh getters, method wsing wWisualtetce and lags ~~ e ple Clase — public cass Exarople Sting Wame ; Public String getName ¢ > f We Betuwn “Tad 5 h £ 8 Example Page + apex outputlabal > © Ahem Nitgualfetea page called : birormeff it woke QetNome () g 4 the por close. § Exampk page Capex : page : comtsollug = YExarmple"> opersoutputlabel > youu name ig f {rome Oukpud [ey &) besiting The alusg into Apox vassiables ror Visual $3. Page - This is called seacyrvite Operation on the vasiable. BE hers pablic oid or NR g this. ee age; r £ (name Prablic _ setNawe (Sti . ame = SS age =O, 3 ee Aly public ran gebigec > betun oge 5 Public oe getNamec > £ Tetuwn ‘san kurmos. ; 4 7) a 4 poe Caper: page contsollas ="Exarnples "> 5 Soper icubputtabel > Fiageg ~Apoxioutputlabel > 2 {roume % Noite an apex class to dotmonstsate Seltesy mnethed 1-2, Pasting the values and sawing tha valuss to Apex Vastableg’ Apex class Public (Class Example! Public Stoing ‘rare 5 | Stoing gptNawe (> deturn ‘arn ; 3 Puble veld stNarne (String name) £ this.name =name y) g & WE page apex page contsalle = “Exarple| > Capex form> Sapet routputtabel> Entos Name 8 $ {nome g <(aper foo NX Copex + rae — We Yan reethads in @ Sing t ublic amlogen sak; got 58 “be ON RR RRM Rm RR eR mee as How to call the apex toathods (1 a Visualfidee page *— Public Clax Perro g Public pageReference Show c) g Betuwn dull / thon we give Tele relirit Ail coma back to the Saime pag. 4 Caper : commmandfatton Vale = “adic nection 2" Pi shotw} than coo cfick on the “click” button tt asl invete Pogerefarance Shon d) nethed —> Pagereference iS the deturn type oft toy emethed that ne howe called -frope visualfetco page . Public class Example | pisblic Sting ‘pawn » Public. Stang getName C ) TokuwN Name ; 3 fesblic void set Nowe (Stsing var) this.name = rane; & Public PageRoferorca Shonc) OMe = ‘This is Tey Tane! +I; seta Nall: é > 3 4 apexipoge Controllers =" % F ne X [apex oulputdabel> = ake ey ‘/> ="dlicte" reRardap ="one" action= "f{ show Z'/> id ="0ne" > lname} Se oon a ee ee ee ee A\b a Strople apex clay to peter addition and wubtyactt on based on the button you haua dlicked. Public dase Grample | 7 Pnteges buakue & fqot jak; & fablic nteqes atialua F get ;sat j2 Public Tavtegas verakt {get set) & Public. Shing epuation fae eo 9 Public PageReferonce Subbt ) f verult =avalua—bvalus ; Operation =‘soareactton'; Tetusn Nuh; g Pubic PageReference subbe ) Degabt = Aryaleee-+bvalees > Operation = ' ADDITION - vekusn well » 3 Capex: osm > Capex :pagepleck title =“calucalata "> apes: page Aleck8eation item > Ager: inpertText ualue = "flan You have Pasrfoomed g {operation Llovalua} ard fi buclue} are the wetuke fLoesult § ae tom> dann Aman ~ aN RN RRR RRR Re RR me eee (. 2. a uo, y dist intauction g G Hethadls i the List COLlEcTTons (17-31) Arssarys Popa to dlisplass areas Of records ty Page block table Progrars to Crate picklist fied my UF Fage Using amwsaug irs Apex . Difference bekexcen Arsay & collection, &) See 4 - Proguary to Permonsts ate Gaga of yn Ape. ~ Exounpla Programs tying Let WN Patt, «Set trhoduction < . Mathads 19 gob «& & + Program to Pomedg rat usage of Keb in AGeox . Exornplo progfearysing cating Sat Ago 8 uisualdbe ap re ion dy e, Methods Ty Hap : Prcgaarn fo Demontteate Grage of Map in Ape y . Excanple programe OFNg Map rex uicuale. Exarnpla to Cxvate Dynamic pitelist sing collections Arras - " Asvay is acollection of Srmilax cements , whasxa the memdy is allocated Sequontly . DatoType C] axraymarne = neva Pataryee[si2e] ; [/1Hs is called dynamic declaration DatoTypel I csvay nore = new PataTyec 1 £ valsot, Vals# 3? ; // : Static daclaxodey Trtequal J masks = New Intequac Tf ©, 20,39}: Account a1 = nen Account (names ‘Saxn)- Account a2 =e Account Croume = 'saun') 5 Account C7] oc = 1H Acgountes fa)a>4 Staingl I St =nw Swirgc 3f “ran, ‘San, Cran § Steingt J St = nen Stoing C4): SICo} =Akumas : SLOQ= ‘Ravi Qe kioita a program to dis plasy asvas of Stsinge in Pog alock Table fur Public clase Avrag Excarnplo i Puble Ctvingt 3 Yoyval Eset; got; 9 Public Stsing vane f get ser; % pablic Assay Exarnpled) g ‘name = 'prarad' ; 7 nen SingcT § 'sam', Gam, NS. 3? Oper: Page @otolleg = “pray apa: fooan > Sapay re Caper: rng \ mytal 9" vos = "a> Kaper: Fes LayA a Soper { name} £ Account At = neny Account (name ='sash;', ordustay = Banging » Account a.=nen Account( name =" Rew! ', Trdustey="Banting'); Acomunt ag =new Acepent( raxee = ‘prcwteen’, Trekastey ‘carting’ ); tryvol = Naw Accorun tc J fay, 034) 4 5 apex; poge Contiol (ay = “Avrayexarnple SS Xaper:poim> Capex : pageBlock > Sop: pogeslockTanle value =") myval” wag e's LAporrcoluwmn Valew = “Slamames '/> SOPexicolumn vabu = "Fla. trckuatey 3 '/> f Inova } <(apexrform> S/apex:page> pterlist csi ng Selectoption Salectoption, from Apex — ty COper: Sclackdist Siae= y's “a ket 'scap'/> i we "SOFC"/> » Seloctoption Op3 = Ten selactoption (‘null | '~Wore-l)- Lelsctaption Opr = row Celactoption C ‘ore’, Ntan'); AA RnR Rr AAA ame AY solactoption op2= nen sdactoption( ten, “feb', nenyoptions = Ton Seloctoptionc 3f 03 oP! ,0p23 § 5 apex: forrm> Caper sSelactfist side =| > 5 < (apex -gglodopions > ~Popericalacktist > Napor: soloctlist dive =“ Cs Sapex:solactoption ‘temlahel = “Java” ttermUaluo="Taue] <(apen:celactoption > Sapex:seloctoption ‘itembabel = "sEOc" HomValua="sp "> (apex :selectoption > <(apex :colact List > Sager form > C(aper:page> Collections — Diffesence betewsoor Foray ard collections . Avra collecting . [-shewary ic a collectionot (BE ts acollection of homogents a8 Csinilos) Cloynants. Q.AArroys can not Grow ord shrink dyramtally, 3. Avrauys can be acest Posters curd leg ranrrory . ue ORgeMa MOSe Yer - — Ust 1S an i > A list Collection of clamante that arg Clistingerished thois Mrdicoy. bi > ust dae fn he of any cia type pwmitive type, collectione , sobjocks , sew -dafined type ound badltin por types - RAR RRR RR a ees Bnkx0, Under | Brdew2 inden 3 Index a Gren | elas yeltero | Red Black] — Inrestion Sees is prosentued. can grow yramically at sun time , > Puplicate Ualuos are allowed. = net valeos ase acepted. Methods im List clas .— add Coblect)'— Adda an clrment to the ondof therlit . add_(Integos obiect) - Drsests an clerndnt into the list at tho Specified \odex position. add Al| CHist) + Adds all of there alemerite in the cpecifiad bt to tho list that calls tho Teethndy Both Liste musthe of the Sarm type. addt!| (set) - Add oll of the clerrants in spocified Set to the (i that alle the. rfothe|. The St and the list wart be Of the Sarre type: Cleaure y— Removes all dlemente Prom a List , Consegtuantty Cetting tte bot’ hogth to 2e%0 . Clone >'= Mages a duplicate Copy of alist: deepclone (oolean ,Bealean Boolean) {— Maer a duplicate copy of a List 6 eOblect secords, Indleeding tha sChicct records kK thorcolues . equals (ast) ‘~ Camnparey this list with tho Specified list and sotum trug MH both liste ax cqual - Otherwise doturng alu. get Enteges) — Returns the lect clamert Stosedat tha apocified index. get sObiect Type C) Retusne the tokun o thot mares ep @ ligtof sObiacte. hashCode)‘ Ratusrs the hash ~~ [2St ard ita Contents . > the le Baso damneants, an ttevads’\ fh this lst. TAERmptyC) = Retume tewatadc ) = Pekcenns a ® varmoua (Inte: > Qpreifeed, tr tte (ict alament Stead at the Jr sets tte Specified wakes fob tho Claimant at gue ‘oder, LZCO) = Potusne tho rembey of clorments ty the list. Gost ‘= Sorts the Teme tw the [ist TH ascerdiing Owns. ih tho Qhamant Chat coag whowd | oe a a a A A on a A2\ ae List Stv= Pon lst C); Stsing Siz ‘saxo' Sting S) = (Rar; Sting 88= ‘Raw; Str-ackl (st) 7 Stp-add (82 5 Sto add (1,$2); List Realist ETON List > 5) Eimaldsct acall Cota), String x= Sto: get); /] Rawi s Woite a psogsarn to domenstsalo the list Public cae ListExarsple f Public List result {set ; get; Public ListExangle ¢) - i TOME = New LisrsSteing><¢ eau. add ('sam') ; Boalt add (‘sarn'); Begult add ¢' haxi'); SeBult- add (1, ‘keumas, "5; 43 a apex: page Controle, = “ListExample" > apex: pagplock> Capen :pogeslocctabe ‘value = "$1 derelt $ “! vay stall Sapericolermn ualus = “$ 1a g's S (apex: pasealock Tale s Japon: pagerlock> § > Sage: page > List of objects Dero Petblic clag Liste: Public List apex: pageslock> Caper Golam Value = "f (a nameg'/s. ~ Capon: pageSlec table > <(aper: pagecloct > (apex: page > Cseote a listof Apex class objects 4» global class Student g public Stsing nove £ get; et; 2 public Trieg Age fget; set |p Pablic Student (Sting name, Inteqae age) £ b this. Nae = nae » ths age =age ; § 3 oy List Exormple fpex — Public Clax GStExarple £ pable List Student > sepult sot; gek:B Public LstExamele() . £ i veult =ren List ; Stuclont Sl= nes Ctudent (\ Student §2= my Stuclent (* ape: page oles = “ListBxarnple US \@per : pagerslock> Spex: pageslocetanle alee =f) aout Yad s"alts Napex celersn Value = "Fla-ramed" > AA Rr narra eae eee As apex: foom> : SOpecccutputlane jfAP="Sye" Se you have Selocted £ (mnyual 4 Apa fd XX ons Tornag = nen Set Q) Set acc = mon! Gal ): € SA< Custorray__¢> Treycustonrers erent Set Public void add Cobiect’) // this amethad willacd clorments to the se Sot Tamed = New Cok < 5 Memes add (' one’); Names s add ('te00") 5 “cies. add Cone"); NOTE cel fail not allow duplcades , but Poe innage it will ‘not soise any awd) Ht will Not tafes Vales. public void adtAll isd //This method will etal dormers 4p the Sok List wey lit =hani Lise 0; woyfigt «acd Come’); onylist - add ('two') Qt CShing> Poyromes = Yo Sok name =e cot a > sparraay . add (‘one"); Tntegs, mygize 20 // THIS will rts 3 arn Stowd to my gre Variable | g fy Stages index) /7is rexthed enill Pernove ‘the clornonts at tha Specified indax - Tareas. gare C1); AR AAA ARR OAR RR RRR A2s Erampes sivite an ager dag to demonstrate sot . public cha SetExample - Sok Tarnes f get set; public SebExample ¢ ) g ake) Mares = Tow Sek Capex pose Bloc k> ape |fagesloce Table vale = "8 hrames3" vag = "a> N/aper :pageslock > ~/opex spage> —> Lisite an aper clar to add listol claments to sl. Public class SetExarnple i £ Public Sot "ames fet set; & Public SotExample() £ il list voxglist = Ton List nomes {get set} palic beolean teat { get; set; 3 public GotExample ¢) t . List < Steing > voylist = ren List < Bing rl, omylist sadd Csasbi'); Trngglist- add C' wakesh')» Mamay = ren Get C Shag +O; Names acd C*saahi'); Marneg add (wan"); “rarnay. act ( ‘kwrsas');, test names. tckaindll (croylist) ; & § \o Visual{erco peg Naper:pag Gontoolles = “setexample "> Sper : pogeslock > Caper :custpectlabal > Pltert.% C/apox : cutpetlabol > Naperrdatalist valuo ="6 (ravnes" vos ="a'> § lay ce WO oN >

AAA RR nm meee sent, aed Thurs the Covregpording valus if Siac Retuni the no: of bey-Valus aire in the wep, valua.c- Returns a litt that Gortarng atl oF the Voleg he ‘ree.p ry aunbitasy odor Set Of key» teaag CaN vot bo deeplicate Aa Bet of valuag: 2 allows duplicates. Map< Dnte pes ASkeeng > MEY = Meta Mop tuys = List Valens void ped (key value) vo. pet cy ‘sar; srn.pak (2, Rave’); ".put (3, Spurcas »; fi "saw, 9 > "Ran, g—> tumany 5 sthicct got Ceayp), than coe give Fogg tt coll votuay vals Stotry xX =. mt C1 y= Sany String yarm.gee (3) Dkurtax’, > cok Csobiect > keys Ct ABP woe we [his eethed coe call get Say ¢ s¥nkexekOy, =341,2133 ist Values FE will set list of valeoe ty the MHP. i List SSteng> val = 1. values ¢ y= f 'saro') “Sauro, eurooss'S \A Public List Sting> rmyretall Egot; set; % Map royseault = Ten List SSteing>O; Toy EAP = Her ie y é rrvgroap .put (*Hyd'y SSaktwh")-- » Tmeprenp, pal ( nesangal eae vy rap, put ( ‘Kasinny 3 peblic FogRofessence rote agua. clas S ; fe Public pagerepasance displosye 9 Fagpatt =rmytoap. Valuce (9, ssettrsn Null ; 4 qj Re RRR RR mn mem amen aay SapcSiving , Hist Storg>> “roy braurehes = Dn Hap >¢ >; List hyd snen List HOD = NOW Ustesising>¢ ys Hyd add ('kast"); Byd-add C' bhalarnpali'), tyBranches pat CS HO8", wa) Mybxanches. pud Ci wos’, wavs) | List Stung > adi = res List CSthing> ©: Ady acd C 'Hanchigasl > Adi eadd Cogedanasi Hybronchsd - add (adi ‘48 Set Ching > keys = Myboanches teerg ser) - pO (Stsirg + roy) & Salectopti on opa=ren Seloctoption(ss). J % Ast String S val= “my brcurches get Ceity) , \S Public class DeperdExarnple ¢ public PageReferone showed f list beans mybrances. get Cnycity) Brauch. clear¢ By AdCstoing «:bxan) £ C Select option opl= nen eloctoptionc x Ne. © > bsanch add (opi); ¥ 3 detum null; Apex close - bist SsuiNg> SO, fon> cig oc gery List SSteing > hyd = Tea List s Stig =O) Hyel. add C'svaagaa') ; hyd. gall Cbragas'); Public Stving inn Nap bang= new List Q) 1add ('Ecity'D bag ach (*Masthali'); srg bcunches «ct C tiga! hyd 2; “poybvaunches « pk (S Bang", bang); Sek String> lays = my branches, keySok C) City =e List < Selectoptionr( >; branch = non Hst< Salectoption >¢) city. add (meh Solactoption (nal ‘Nene)), List Hy =e List String> C)» Wny-ecdd Cine"); Fo Geaing a: keys) f Sdactoption opt ster Selockeption (2/2); City accor sy) g $ P Af Page F Capex :page Conteolles = "Peperdexampe"> bso Taper: soactiist Size ="(" Ml ="One"> apex: sictopions value ="f “we apen : solactoptions > < apan : clectlist> . <(aper:forrn > Naper.page> SA Example -— a € mae Purblic. claggi™ hst® eed f > Topatridel Pept set 9 Public Lists Maas Conteolles > 8 (opeigields = rea Mapc sting , Sting >O £ * Seegt Name! => ‘sonny! ,'lastncune ! => “Applessed ', ‘ag => qa § 4 poco Cee a aa A Ae a ee ee ee ee ee Ag\ Public PogeRefesreinca submit Fidd data & ) £ chore thing Tntexeating hotth Dnputc 2 Solus) val Public Void & desomething Totevesting hith Input ‘pputficds . patC'age’, Cotes. valor cae “94 Cage’) 3 oS apex ;cutpukpars| td "bogs Refoud = “block > apex: pagetesag Ete < (apex: wepent > Custornas = [seloct Customes_ianns——¢ Balance —c from Curtormmes Cheese Pecof_-c Averupes (' Aadhar coud’, ‘pancasd 4 Q) hivite 0 qussy to fetch tha [ict Of Dds & cestornas roxnag som Gutorauy object bhasa Proof is dadhar cod dH Gosepdt ard Votusid. ~~ : Lathe You want fo easttes hI Snore than ore value then Docc c=. “PoanpCN 5 voteuld List < Gustomax, a Cus Qs Cexgtornds norte, Cagtomay_¢ nhosg = CAerdhaacasd', ‘passed; suctaid fe : ithe ¢ ; Gees ig te the valuo spin the Specified fictd aame “atehes the characteas Of Che text Stsing in the Specified valus. the LIE opewaked im Soar and soxL ic Gimwilon to tha LIKE operatdh iy sar. em RR me mn ena pss De provides a mechanism $B matehing Pastial tect Stoings yd includes Cappost 43s nild cards. > the %and_ nildcasds are Supposted fedthe LiKE cpesate > the % pidlcaxd mnatehor Bevo o Trove chawacleag the —hildcase watches exactly one charade » He text Shing iy the Specified value amugt be entldsed iy Lingle quotes. ; > The Like Opesatos ic suppdlted 1 Byg tields only ho AChE cpematdh porforms a Cae insensitine wrodch , wnleke Case Sonsitiua Match in Saat. Eqr Setect Accountad, pivetndme lastname FROM Gontock ’ WHERE Lastname LIKE ‘appl_ x! Ini Tike Udder. equals any one Of the Specified vakwea tn a WHERE. laure - AAP Select name From Account WHERE Billingstato ay Cealifornia’, ‘nevoyosr Q WHERE clause. FS tg Ear SELEct Nowe FRON Account WHERE Bilkngstate NoT-LN (‘cali e's ove!) Suby Lasy the qansy coth In a quassay tip ~ i b8rite a quasy to setamy list Nhat Min ret hore. any open Oppostanitieg © Co Sevect Id ® FROM Account, WHERE Id XN Bho > Fecount td is alookep field nity tm the Oppostunity WHER > clegad = fale Br sey CR Ah RA nm mem mR mee Ast eer seuect ‘Id FROM Opportunity WHERE AccountTd NOT IN ¢ setter Accountid FRom Contact {WHERE LeadSoure ='Web" > NOTES tlhenaves, 0 cseate @ reastes -datnil & loop Pele! Sd of the wastes, Sucosd is Stovad ‘wn thts field. Date formate - Haken you uEunk to use the chic formats cin qaasgy te Should be any ne of tho boloc formats Fovrat Foemab syntax Example Code. only Y¥YY —MM-0D 1991 -01 -0| Date ; time & Y¥y¥-Mu -DorbhmmSs+ hb aM time Bore. olftor S3+hh Eq 1991 01-0723 01 101 +01 100 YYYY—MM -DDThh Sym .SS+bb | THI Lemar: «sa Lintt to Spocifen the Maximury NuUmbes Of wong to Seton. Be caccr Hess List Fron objecttype. CHere Conditionex pressions] Limit Numbas_of_ sone Eq- Select NaYne FROM Account KIHERE Industey =‘ Media’ Lim NOTE You can't use a Limit on agqpregate Function, but does ny FS exarmph , the ol loes SE uct MAX (Or Date FRON aN R SERSET Use OFFS! 0 Stoxting Hox Obsct ‘ipto the Degulk Set setusved by yous que. Ft erge. were — Gaing ofrseT is helpful fck Peging Sets In Scenavias whasro YOU Need to pricteley jump to a pasticulas subset Of the entise vegults, lt ee et) foal ee nl ne eG Ast Syntax “ gevecr fred ist Feo Object type. CwHere Condi io Exprestion | ORDER By PretdowmMasByList LIMET numbes_of_ Tors. to-TeLUrt) : OFFSET “Nubes_of_ voNs— to_skip ~~) eye SELECT Narne FROM Meeschandise_¢ \ WHERE pvice _C> 5-0 ORDER BY Name Limit too OFFSET (0 Groop By + bith APT vession {8.0 ard lateg , you can use Geoup ay with aggregate functions, Such as gomcy & maxc), 10 Semmarte the dato and enable you to rollup Qaoy Sagults -sothes, than Having 4 process tte ‘Wividual secowls in yous coda Syntox— [arroup ay Fiekd Geoopaytist J Le a LeadSousce FROM Lead. ep SELECT Lead gowwe , CouNT (Name) Feo Lead Group By Lead source Ber Sevect Leadgouxe FRoM Lead Groupe By Leadsource . NET You oust Cx a GiRoup ay Liat clause ard an agnegated Eqr SELECT Name, FRow Account Geoup By tro | Liman o> ~ nis ns the queasy to caluculate have to maintain that logic tM Yous, Geen Ge GRovp By Steb totals code « Syotax = (CGiecop By Rouwp fictive fdkdneames,Hekinawnes ) | RN RRR Rn mn ee en ten eeennnaanan As} Fae Rolls tha wesults up by one fad SEtecT LeadSource , COONTCNAMe) ent FROM Load Groop By RaLLUp (ead gousce) Eqn Rolls. the reulte Up by two fields SELECT Status , LeadSdusce , COUNT CNaKNe) Cit -FRom Lead Group ey Rowup Cstatus , deodSocexce) GRovp BY COBES this is porticubey, usctal iF yous need to Compile cross — tabula Bepovis Of yous data. ‘Uae GRoop BY COBE ith aggregate functions , Such ay Soucy sahd ceont (Field waxne) Santon [Group By coge ([fietdnamet fetdnames., PictaWames) | FRetupns Subtotals of accounts fob Combinational Type. aailing city SELECT Tyee , Bill lingcmenntsy , GROvPENG Crype) ETYF , GROORING, Gillngiountey) grecty ‘, COUNT Cid) ects. FRom Account Gebop By coBE Crvre, eillingcountsy) ORPER BY GROOPING CTste) , Grouping CBikrqCountsy) HAVING ¢- With APL vassion (8-0 and lates, You can use A HAVING Claize witha GRovp ey clause t6 filteax te multe Ietasned by Aggie ale functions , Such 93 SUMC). Syn ion Cthuterg, having Gorditionex prossi ov | QU: Setesming hoeo many leads ass. sian Source. SELECT Leadsouxce , Coon tCName) FROM lead Geoop By leadsouse qo + Genusate more SELECT Leodleertse a By oS HAUING, fy Baar Re atth cuplicate namag ee fy: (ad) FRom A Geove By name HAUING CountQd) >| ee ea ee le el ol re re Abe Relationship quevieg Wihen you Laant to weite a quesies based on pasent child welation ship will be using Wlotionsbip queried on Stardosd & Custom obiectg. T —SThose cure tuo typea off selationsbip Gpasrios . D child to podent sdationship » posent to chile relationship child 40 Paxent welationship ;— oil fps (ean Relation ship pam ACCOuNE, Th the abow ciagrarn Contact is a chil of Account Object > T tho child to pavert wtelationship welationship ‘rayne will de Fonant Object which means Foriegn koy ely aa cae in fecount ebject Eqi- SELECT Contact .Fixctnarme ,Contact. Acceunt-Name -fsom Contact | Eg2r bsitea queasy to Fetch ligt of Contacte ard Accountrenrg from Gontact objects Whose Account. Drcustsy = Medio’. SELECT Td narne , Account: Name FROY Contact neere Account - Indus toy = xedia! child NOTE Whi wwe use velationship name Cuda obsecte Th SoAL queny be should apperd oblect in “the csolationghip Tame. Egie List ch = (elect ty iN 7 AS 0 Foor child-c ° geregd<<]; mt 28 FrsstNawme , Podwnt Object Object NOTE fuhen youass waiting a $som child to podant 4 ae ea] daationship aleoays Posent abject Herm wel velation ramswill Bo pastay - detail field Nano) lookup field name. Peete ieee a On None Alby J labsiie a. quasy to fetch list of Arantactions along with Account type ind customes Narmg whose tsansaction type ie daposit : NOTES wastes -dotail field uo the transaction ‘ie coatamensdatils Cc List cont £ get, Set; % Public pogeRefo sonce Showc) f cont = [select id, name ) Account: Noun , Account Industey From Contact Hrvit 5]. deta Yul; & 3 NA page = Sapox:poge Contsolles = “child pasaint" > apex: pogeplock sendewd = "S| wotCas wor Cont )g > Sapea = popeloctctoble value =" Scone 3" Va =" Sopex: column volue = "fla. Nano % Opa: colume valtur="f Lo. Account ta ~ Jaren page Blocks NA — wre es "Blick" action= fishers 2°¥ “AT A RM Ann an nn nm ee eee as Aus Gr wate a Apex progsan to disphy the tronsaation datotls cling nith customad Nant , Account tyre, city Uaing tansaottan fp cha = Pablic class childpasent 2 pablic Hist tan fgek ysok ;% Public pageRefesance Shont ‘ : toon = [selact Typoag cus Customs als a Account. Type _¢, Custorpes “fitols a. Custams nat, Castors —puiotls city __¢ from, Teowsacticen..c vekuon nell; ; % ME poge = apex: page Gnteellas = “chielpasant" > . Kapacormand@utton value= "elice" action =i shor Y'/> Capen: posplode> AW Accoum ware :f laname% £11 , Pecoun arduthy Sia. fndustey? Xaper sdatatist Ualue = "8 [a -contacts} “von = "b''> & 1b Evmail ~~~ { {bs Assistant nasa ~Yaperiforr > S y+ Pasant_to chill relationship on custonn objects ‘~ Khon You: ae. coviting A geeay to sefess, Custom child Obseck Fietde Prom the pamint child velationship than.web have to Qppord — child object Plural rarne —_v, SEuecr Cusletnesd — Nowa decocantty pe CSeteet pasent nano _c i Age--6 ; (select Child —Noure_c | Pob_c from chills») Prom posent | “3 Wibite. aun Apex progean gt Hatornes detail olong with cea details Of the Gretornens, oshose cons Apex “S “~ “ee fe , Ust-< customs __c7 Oat fept;sobe , Public PAKRefesone Showd¢ y § =[selact Castorme “ano, Account type c, SNR ARR RR RRR RRR ARR RRR AS Cooloct Type. ;Amecent Crom Transactions) Frcro Cersto sess C) J 7 vetusn null; § apes : page Controllers = “parent chi (ds Open: fos > } yw a Capex :commnand@ation Uahua="cliee cettén="f Isheww Go, ~ Spex scolawn valu yo "$ 6a. Accetunt type_c &/> Apex: column > Spe Color > 1b. Ty Rec} S(apex tcolurm> Capex: Column > & 1b Amount _-¢ 3 NJopex: columns <(opox SANS Kasper: colernn> (apo: page@lock s <[oper:forrn> Sopex:page > bb SOSL Statements t- LOSl Statements evaluate toa lice off obiects ,cthene cach hee Grvtaire tre Sawch seralte tha particule, eCbicct type. the Bosubt lists axe always veluwnedl ‘in the Sune owas ag they corre Specified ‘im tha SokL query. > To sos quay does vet return) any records foo + Sfecified sObiect type | tha Search Beselts “incluce an erpty bet fd that Lobsed - : — FE example , you Guy debs a fist of Cccounts Contact? . oppostemnitien ard leads that begin adith the phsage wp. List< Lia T the Fowe-Com App, the valus of the FIND Clauge fs cermascated with singe quetes braces . ¢ For Ege FIND f-map#3 BN ALL PIELOS RETURNING Account Cad , Rate) | Gntect, Opportunity ) Lead . From Searschlist , you can crate Cwrrays cadhs oe” ; om a t Account CJ accounts = CEs > THYRUuG = Seqaich, qeundy CSOSL. _Seasel —Sbivg) the folloxirg example excessdSes a Sire Sos. qeeeny Sting Sting Seanchyumny = ‘FInp\'Edgo#\! IN ALL FIELDS, RETORNENG, Account (id name) ,Gontact , fad", List CList> seaschtist = 9 A seaxch, Pony Goaschqusiay) > Dyraric Goel Statements evaluate to 0 ict of Iiges of cabsects | cohena each fist Gortaine the, “gasch vesulic fa, Padaticulas SObjecktype- tho yerull: lst ase Altoays salud “in He Sane tog ag they cone Speeifiad in the cyrame Sose Qeasy , D> The Search GYutoy method “can be sed chara cuey an inltng SSL Yuassy Can be ured 7» Such ay iin wegular atignmment Statements and 45 loope . SOSL example. Pearitc Lith Sharing class deferonceDerGonizellers { public List coppostenitys optylist { get ; set: buble List acclist $ get; sok é d Public PefevionceDemoGonteolles ¢ y ; ‘ Public Void scelpomo_! g ® Optylist = Neco ti Re) leadfist = Need hist ; = as t Llontact > oO; tS ACcotent >); List SearehList = CPIND ‘text! Dy ALL RLELOS ReEoRNENG Account Cid Name , type) : Comtack Crareeerratl) ; Opportunity Cname , Stage Naxne) , Lacrd Ceompany Marne, Status). TOR RR RR mR RR RR RR me A 48 acclist = CCList Account >) cearchlist Col); conist = CCList ) SeaxchList C2} Jy leadbist = (Chist ) SeaschHst [3] ; 4 4 Vf page < apec ipage contoollers = “poferencePernoGontoulleas’ > ~\ Caper: Command Betton valua ="\show ‘ecords ORing gost" Qckion = “f'lsosloemo_rmathed §/> Kaper: pagesleck ttle =‘ Aecoiants "> Caper 1 pagelock title =“eontacts" > ie Taper: pageSlock Mble valesa = ‘S$ teomuist 3" Wat = “eon c ¢ : ‘ <(apes : popBlocktable > ; <(ceper ipagealeat > ‘ _ ; me! “ Caper : pageBlocie tite Ror > SSVetglist $" was ="opty" > Apex icolerin Qual = “f lepty. Ctagenamne Bl> <(Apex : pamBloamaie > Soper: pageplack 7 Sapa: m> {oper page > a EMATL PREGRAUMING, (50-61) (Ls Dytoduct’on to Evil 2. Types oP Ermils Dy single Boral} Meange & mathe ue Single Ereail Heyage Exaxngle Using Apex 4 ee) ¥ 5. Hawg trail Meszoge Zotseckaction eD 6. Mass, Erni Hexage Example vam ODM Hoe Ty Attaching Fier CADE | x8) to © ae B. Adeaching docrmonts to Outho; Erni Mertag, S.. Fotsockuction to seu eR Hexage lo Eravnnge. PTO NS c ter “ | “Ss Ewnoft pe sarmmninng f— [han you cant to Senda emil fom tho, Salegtdee to the extedmal gystor Stseciaing a Troll from the tutesral system 40 the salesfdee the We (le Errol gomuica. thease are 2 types of erik phat we hau . ) 1) Tyeound email meviaging ) 2) outtourd anal Thextaging outbound email’ This ig used to Sond, BH amnil to extearal, Sytem using oper ecto. thene axe D types of, axdbound Emails. y Singe Exro8l Message a Mesa reall Hégcage . Netaging Neu Sperce, Provides claeg and mathals PS Salexfedee oustound ard intourkd email Ranctiomallity - D Sialcavestage TRS Ie A jstantiates ay email Ebject easel B sending mH Sirgle email Tra gHage Hesaaging Singer Heage somnil= nen Hessaging safer Heacage (1 5 This case Gotaing Tnethads of Cending Single Crmail sonenoge. khan ee emnt to send a mnexage firgt coc haue to coente tho cbiect of Singlocrmilnerog. Tho ligt of methedls auailable tn the Sirge Errail Megrage aaa = Getbec Addvesses (Staingt 2) this Methal ewill Cat Bec Acdrex to w il Should ke Sort: he can gat upto RN @r Stringt 3 to becaddses; = New se, v nyermall cab eccfetirenes (dec veut) ~\ == > Sok Addvosces Cixi *& thig meted iN, to who the Yall Should be Sent. Ke. 2 enroah) acdhweg | vn na Stange 3 s ‘ci@grrail » ice) en THY CoAdd 09809 Ctoccadd vers) ; DS SkTHAddvep¢0g 3 (Stange 3 1» this reathad will cot the addseg, ne can cot upto tt Addresses Sf AN AT FM AR RRR eee eee Ae Ey Seige toaddsess = roo Stvingl I$ ‘abe@grrall conn’ ‘xy2 @ genail: Com! » reyernatl . cet ToAddreagag Coad); ==> Sct Subject (Steing) thig Ymathed coll Sot the Seebject of the rai le _ qr myerail, cetsubiect ( tegt Errail!); , ==> seeplain txt Gay (seing) this wmethod twill Se the "Tesck ory of the rel sr Toy ermal. setpainiact Baldy (ni $ann'); => cettrol Bady CSteing) this method cil! co the rain body of Che moll. €Qr ryornall . Sel Himl@aty (‘ this is tha line fF) Registsation Jhi>') ; Example - fee clase Public. clas rrondlag £ Peublic, Poge Re-fewance Shewo¢ > Messaging . Single Exrail Hemage veg = Te Sw Sting toaddweg = mon Ste ¢ "mq. seb ordelgeage 6 y Stinge a Stuingey £'a1@ greal. con’, (98. @ qrenil-arn'§ ‘ Qa. Ctobcarcetreas 5 Skevge to eas = TEN Sting 3 i ‘CL@q rrail: conn’ Re trngg Sek Cc Ackisesses Ctoce addwesy) - eg. setSuabject (Coat; msg. set plaintext Body CHS. Ran!) y 475 @Frraid Comm! » oe OT mr ROR RAR eee ee ee sk Ae rrag cottitmalecdy (ches ths is the line FS Wegistazttion <[bi>)5 Mesaaging -somterradl Cron Mestagirg. cingbrmnil MeseageC 3 Smeg 2) are Dull; % 3 >" ee 3 Sapexfooms S/ogex. page > 5 Ln te aboe Peogsarn when we Wont to send an Enroll we 30 the Folleewsing syntax, Public Messaging. sencdEmailReseltl I Serdernat| Crexsageng.erroil cy exvaile , Beoleanoll Botting) thic Thsthad Gye Ket of @ros{ oblecke Tratentiated ith tithes SnfeEral reriag: FV hasserictlonaae >In the methed Ho boolean Fasametesy is optional. whan yous give the bedlean value is false , if any ere of email is fatled ‘re Stops processing all othes emails , i boolean value ig tus. EP ang one of the ermil ic failed , it digcardad only. that renal ard the rest of tte Tratle poocessed aseexeially . Send€mail uersage ne Syntax t- : Public Messaging SondErailResult C Lute coun eond| Twossage, to @ Vecipient (ist that Consists of Comtasts ,leads , pesrson Accounts, OF UBeRs YOR Cay UieO 11 Sales face. Memoging MastEmai{ wextage + This class has alll the vrothads defined in the Erenil clase Gnd ales Errail base clase wothede . Tm a ORR AR AR ee ee os Me Methods Public void setDescri ption(stsing desexiption) t- This will giua the duscription about the wail: public wid SefTuagetobiect Ris @OCT tadget chiect fda) .— he can add upto 250 Ing pe email: DF you specify a walgia, fob tho Taoget obiect ‘hs field optionally Specify LIKGETDS Gog Hell. Public void sethokds (IDC J Whaklds) re The wales coun be any one of the following 1 Contsack ; cagel ypposturity and product. Symtox = Messaging. Maskemail Message Trail = new Messaging: Hascernas| HeKoger y Example Apex Class Public clase tertenndil R = : Private firal List Conlactide - [ Peablic List Cen; Public testerrat| Gipexpoges. StandaadContaollea Contsolled) g Gon = (select Td from Contact limit 250] > £8) Cintegeny 0; i<250 ;i+4) g ‘ Contactids ach (conti. 2d) ; 3 3 > € public wid serdevrail ¢> { Metaging Nowermitesage vrai exe ry. askErnal| Messager »; “N. _ : ' ® : ida) 2 oging. MasstrrailMessager 3 bred 4); ATA RAR RR ARR ee apex: pog GthndadGritsollas, = “contact edtonsions= "skal!" ~ ~ Pe Ematletle Attachment ‘- essagirg. Ermailtile Attachment {~ > EnvilpileAttachment is used in single ormail roersah ‘to spec attachments parsed Mm ag a past of Teqert iy Othas teamg Cording file attachments in the ermal. Mees = Public void setpionore(Sting Naan) !— this methad cll sek the mayne of the Fle ewhich pe attach , Publc_Ved setbeiy Cplob ottachermet) + rig. wethal will Se the attochrments, When Wl Want to set tho attachments wm tho Blob fowrmet ) tO reed to xe the Blob muhods. Public Ctatic Blob topdf (stsing) ‘— thie mrothed east the Specified Seving tte pd? fdrnat . Public Stoke Blob Valuect (ching) :— This methal cast te Spacified Shing to Blob format. Public Stvng toStsirg (Gleb b) — Db weqiwe a elod valus ‘ts Conuested Into Stsing . Public void setContentTygre (stsing) i this ell specify the what of attachment Contant we have added. Public void setIntine (Benlean b) ~ then you giue tous tt doesn't respi any Actor when the Content is. peng o.. TO attach a pdf file in email uo (tke balou. Fae. qptpoxametese (put td erg Wd)? PAL. set Redirect (true lob b= Ref. ¢ OQ Blo if at Meszag ‘vg .Ermadl 6 Achmmor Tmyaay = Veo HRI ging Errail File Attachrront (>. Messaging ig age em TH Netoging .SindeErnea| rm . eagec, em. set file ttachments Crows Nesnging -EvraalgileAttachnmontCJ Emerg) “SR RA AO mR MRA MAR ASG Create. a utgualfosce. page bith in a abtachrnant pd. Kapexioutpetfiokl value ="f lsccount. Prdusiry Ps) y ~<(aper :ageslo ck> SJapex:page> \ed\ LAbsite a Program to add visualforee page ay a attachment to rail “ww Pat format. per clase Public clase MyAttachrent * Recount ace 5 Public String noyname Peck, get; Public myAttachment (> ae act =(eelect td name from Account RhAe Voure = rey name brett. 4 pablic pogeRfesance Shoe > & Nextag ing. SingleeonaiMegsage areyrnoi| = revs Massaging. SingeEmai| wessagec yi Messaging. Crmileledtrachmnant tratlevan Henagin. Eomail PleAriachmnant ( > rege Refanmna Pdf. = page attachmantdia gy PAP got pasrametennd 7. put Cd! RO ; Pat. SekRedivock Crsue)) Y : % Blab-b.= Paf-gebcennec) Blob b= pdp.get Content Pratl. cot pilnarme O OIA fonail. ser Body(b). ‘lprall nAN will); Stsieq to CTS ab(@Dqymail-com'Z, « SurTe 23 Coad), rmyrnail. sekBatly (62 find the attadrmert |)» Tomyardt| tok PIE ARCach ments (nero Herkaging.Eradl fle, mR RAMA RAR AMARA ERA RRR MA Attarchraent C4 8 meu D5 Nesgaaging: Send Ersai) (nen Hestaging Creal} Fmymal gy. Selwyn oul 5 ' ‘i § As6 ME Page : Kaper y wnput fort Vales = “s | myncerne 4 /> ~ <(aper:fom> oP) Sloper: page> Gerding the documents though trail £2) ) Public ucid SotOreutment Attochmante(ENC J) = this Ynathod eaSil send tre, couinants that Gat get tp the Sales eco ny the real Using Meaging Concept. Sept emate a documant wy saleatske al to Document obiect click on Fries deccement . 2. Etas, tho Tame, desesiption of the document, 8. BolockExtasrat File , Aco” the document Pile & save Step>'- Ta Apex. progeny toile A Guay to fetch the id of the document Cohere document rome = ahiah!. Attaich tris docenent to single Brailneriage Decumnt d= [select td from cocwment here narne ="catiah' Hexaging, SingeEmail Hesage. mail = wen Sinde Brratl Hessager ); nail. SekDecurmenttetachments Crem SPL 8did 8), Example Apex clay Public dasr veaile: z Pablic pagerofonenca SS g Docursent d= ([selott d- phere Teme >! eatign’ J; Keataging . SrqleE Ne nag = Mestagng: Singlecrnd] if Mekoge CD; lS ol rants (nen TOC IRd- id); vag. set ' Stairgl J krish = ren Stingl 7 £ Cabe grat cono'f, MHEG: Sct TO Adtve wes Cerishy; ringg Subject ( ‘Hak'); J aa TTR mR Re RR RAR RAR RAT TAT AsH TMngq,. setplainToxt Body C' Hells"); msg: Sot tleady C cht > How gow


); Meagan Memaging. cexcicrrail (ron Mestaging. single Erratd Menage Srnsg); Tetuwn ull 6: 3 NH Page . Geclist-=nen List O; aceist add Oren Recount (towne =" Fema. yy Qecligh adCore Accocunt (Name = ‘acmnes 3): Dakokase : SaveResulT J 0 = Database . ‘sew & (acti fale), —) thase ic one Ciffesone betucen abwuo tu opecodidens. ° Botte Patabase chy recthad You can Sfeclfy eohe than to allo pertiak proressing Ff tte secoids if any eovdds ada ancountased. Bag peasing + By Poksing the beolean value ae a pasametus to potoh cer DFP you Qiva the fasametes, og -tsuo it any ord cccuye Ht doesn't able® tho opasation to continua. >) Th qo Specify false the vensining PML oe can stiff Cucceecl , Whereas east in DML TP any Oo fails the total opesation is discarded . Eye t == Paklic gapRefoserce show) £ fe Ty tho aheue poogsaum whan 2 Yiue Databaye .inseast OF, i} ony candy cccests tm ang one of the Tecorde a1 /A2 03 the antive cpevakion of Tnsegt is solledbact , —) han you Gius Patobave . west (ace false) §& above Stofement) TF ang ewed) Oocuns yy any one of Ere raconds a,a3103 Oy that second ig tesrmvoded And Satug ie Saved to Seg Patt chagg seat of the Openations axe precessed ~resrmally. SEAL ONL and leops — goat for loops ‘iterate cud al of the &). sOCDESS TERUBAd by oat queasy: The syntax of a sca Jedi loop is erthod 4&(uaniable : (Soql -etxyT) o conke_block & @ FSGiostable_kst + [soql_qtwey]) £ coda _bloct + ae String S=‘Bened' - Fd CAccount a: [SELECT Td Warne Born Account Whaas, { Nang, =SJ) [rows code & Ego wivite & Cade to fetch [ict of accouen' hog © remo IS ‘Siebel’ and apdote ther by =O List acces = [setect 1, N WHERE Ni | : U/Leop thmugh the list and upcot 4B Aecmunt Q1ac KN Se Br writra S Fetch list Contacts fox o_giten oacdunt & Updose Comtocr ernatl city account anal id Arxcant ace =Fedact email Cedsct 1, urnell ¢ from contoat9 Fron Accout Whave Yalow > Say! Ure t / ey Reg” dit Con = Qcc: Coma ; List TmyContocts = Tew List C), 48 Ccowtact ¥ 1 co) £ Yeernail sac .ermailid__¢; Wy Contacts .add Cx) » QO 2) % ) Copdate my Contacts; % EQ4> brite a. cota to fetch all Cre twansgetion Wetonds which 08 Creoked tpstesday curd dotate thom: Hist trans [select Foon, Transaction Cc hase Creatédebte = YESTERDAY] | chatete tran; EQS> bite a code te cect nen ctudent seconle by Yotchirg the dota from Coll obsect wheda bsanch ic coe. tisk Std = ren Ust Student +O), Hist Seellege co colg = patohate qiteiy ( ‘Soloct Porte ,Prarch_c, Yoas—_c som college—c Ahaxe brarch cz'cse'y FACeollege --C3 Col : f Sadantc $= pep Stadant cc; S- Wome =. Naima ; S-RBminch_o = c-braunch__c bat Std add Cs); % ingest Std ; Howe to Count Nwmbus Of DHL gtalornents ‘in a. transaction! — BML stolernents in a. tsainrastion : ge . COP Account a= ren Account (Name ='Soun', J TNBUt DL; Account at= ren Accocent Crema =! % on G Y=?'Bainkinng') ; Trmst 4; y % Fg2"- did Shao) @ & ‘Sony! “todustyy =" Banting’) az foorn Account Line J. Account a= YO TN ARR Ar AAR Aaa ame ee Aob Egpr Vid shed) AS Cntegeas i= t, 142100; Ut) t Account a= nen Account ( navee ='Sayn! , Tnduttsy =‘Bannting!) » ue Les 9 QP) % ” 4 ® : NOTES Tn a Single teaniaction Ge can wot Take vnc than \So OM se » ateronts ~) Eger usid shee > g o $oCinteges T= \< = eorrt) g ; Account A= nen Accoant Name = 'Sarn', todudry > ‘Bainking')- Mrgest oy 'y 3 40 the abow tromiaation Shes an WMndle l6o OUL Aasomnants So we get oxy Cred [eo below? Syston - HroitExaption 2 Too ONY Out Statenngy t6 115] Erde 1S 1 expression “$ishowo 3! i Page dlStadomantcoust Baltify the DML. Opesation Khen oe aw Pasforrming PMc operations on aunty Becosd he. have qoresmnay (rnits of 1S0 seconds fos euosy Ctatonsint- >TO Suppoot the lage so. of DML gtatemmnts a Single toantacion cefrthoet bypatting the govesmas |mmits to Treat EIS Togeaivement we ade buttcifying the operation by acting all te socosds to alst and calling ENO. one Rt. NOTES DF you call OMe operation of the f ' ve ioVE called Considesrod cy singe DOKL Statoment “Pai babeifying Operation, y Gousanay livoit 2 By a sindo ts can poston ‘DHL Opesadions Or Fmaacimeng (Diego sour. Ef you petfchry repose thon to,eeos GH exception lca belo, Sys tern tree : TSRNY TORS (000f Be histlO; 4SCior tty i = 4000 444) A = =' ' ceount a Shen Accoent( Name etestoday | Sodus ty = “Banking 3; ace -addcay : ed g ARR RRR eee eae eee Act mmgant Ace y : List Customs 0 > ace( = ran List O; 4d Cintequs fet; bx= 002) +4) Civtommen_¢ A= Hen Carton __¢ (Ceertowns names renentodasp\): acct. add (A) | “ ay 3 Ansest acct +, veto reall 4 Frtastace in Apex - Tyrasfaca is a collection ok can'roplemented methods. Ths will Specify the Sighatase. Of the rnethod ; type of topes tat ceo Pass thormethod Specifies Cohat type Is giean ag ay out pu. Ganevally the twtesface rretheds ce give it @3 glosof Kayntace Public intestac Exam £ Account Sheco ( String 7 3 ALL the metteds bo th interface a poblic awd abstract senekheds. Ttorface algo Comtoing frnal static datomembasy — the clagg whieh is implementing this interface Shoceld Aafive ath the matheds “ty the itorfac. Er tntausfam tet 8 Public String sheer y Oo aroid ispcd: ’ : 3 global clays Exarnpl inp £ & Public String ¢ ge € a wen Account (Name = ‘sour o > Th gow don't cefing any rrettods ip the interface “t ing an awd. ule CoM Cyoate an Object 8 class. ORR RR RR RAR AR RR RRR een a8 ns A chagg Test 8, g 5 Tost Ho New Tost ¢ » —) interface Demo é il : nd = Shewee > 4 ) FB invertam va can net esata an objecl Pomod= nen Demotd! i¢ vot aler@ty, 682 wotenface Comtering oly tnimplrmanted vrathode” and Static raathods. =) cha? Exam vnplemants Pemo Pebke Woid Shetoe’) £ s 5 4 Dame daes i allocced. Geode’ 13 the Chiect of uke clase Cobich ¢ Iopo-menting tha domo intosface we tre clast whic has saceesfelly implemented intesfac, TES Entesface sefewnce VASIaHe can store the Obicct of In tha above Seemario Camo dats is not allecced. Geox thst class ic rot implemented intexfaco domo, Tnvasface Tera THIS is the interface dofmnedt by the salosforce i apex «BE hag 2 amcathads . é t Boolean hay naxt¢) > 2» AheyTypo nackte) \. Boolean hasnoxt() this Eveag iff Chad ig ounothess itor in tha Collection ful 62 Che returns fade. >. Anytgpe HaKte) + roms, hy, eRe item iy the collection, Roth tha rethode Bins Should be doclated as a Global & public ww NOTES eee cutston Heratde ty thie leop, Tt ie ‘not Sappdted 4c}) Lone . : hs : SHE & Program te create Custer tevatd Class sadlah woplernente Proratcdh § aT MAR RRR ARR ARR een ee public List Account> ace; Public Hovages Gy Public Gakishe> £ Qce = CF seloct Manne fron Account] ° tro- t=O) / Public beoleauy hay woxt ¢ > zg V4 Cipac. sae ) A eter falwo, : eke ‘stun ‘teua; 4 Public Account next¢) £ Weieso) Betasn Tell a itt; Berwyn aft- iy § $ NOTE (- gakiah = Nan) sakish¢) > - Dowat < Account > thes, Since Gakish class as implemented Hesatd interface we Carn Stowe the obiact cf the tatish das in Tevates it, Potastace Uersable ~~ ee drevanle ig a interface th edbich ewe howe Dtowatciclass itaratdc) is . Clase Bened Implaments Do’ Accent x «* | Intastacd THewatd , 80 aa @ C1 E> Lb aS: ee : 7 Can Stose this object 7 jmterface itexatd, Sp clase Example : d, Y/sotish classic remplrnentien ON RRR RRR RRR RRR eee List Account > 0cc; public Example € > ace = non List SAccotent =O 5 peublic pagereferance Chexot ) @onad b= nen Bored Cd f & § Ptoratrd< Account > tb = b. ttoscate OR [I sakish $= b- itesatd¢ >; prile Cit -hasnoxt o> Account @ = CAccounbyit ner: £ ence add(as", Setusy srealh 5 $ ATO Global class catizhItesatd implements rerated gee ; Public Drtogess b Public CatishTtarntd¢) g BC = (eolock name Aeon Acco! foo: eA s " Pexblic boston haswoet y Public Accent mexkc » £ if Cless) SeAausy vad ltt; ede) ace i- tel: g + eo em me ee Parblic class Bermd Lorabla tmploments Lterobla g Public Btoratd ttersatd< y 8 votusy New SalithHtesator)' O $ $ Cas+ - Public clas ExarnplePtematd é Public Let < Account > ace y public List Accounts getAcec $ vetuon aes & peblic Example Ptesatd & ate > Den List ( >: Zz § Public PageRefererce Shoux ¢ 8 Ltowble MY = NAD Rand Ptowable (+ ae Rovatd < Accounts +toap-= my -itesatel¢ > + Y phile Cteat. next oot = nell > B Accoant C= teat. noxetc >: L ence add cod) wo HNP = Melee" action =f | sheen. fe waleam="£ (ace " VOR= "A" > volun = "10K" /> < (apx: pageelock Table > apex: pogesloct.> < (apex: foom > ee ee ae na nen ne ee ee BR Ae Datahase . Quasylocaks Clay — Databage. Quasy ocak Clay toes tha veensd cet satus by bho databag . Gt Quosy Locatd. uetheds!— Those arg 2 mothads HO Ho Quasylocoths Charge et OuasyC) Spr public Steing get Qucsyc) “This methed setueng the queap used to imatantiab the Batabage . Quasy Lecatd cbioct. “I is Vowy ymuch eof cohen testing the Stast method. oe Database . Quusy locates dg, =Patabaso. got auany Locate? CCseloct narne Leon KecountT) - Shiwg Sts = dg -qotquoay(); I) cis = ‘Stléck varne. foom Account!’ =) Veale = . SU> public Datobor -@uasylocatd Treva ivewatcd¢ ) phic willl velar mR Instance of Oytaneey Leccakd Gkesabb , EQe viet yr List Account ace = new List¢ >; Podabare . Quay lecaks da= Patabare .gebaueiny Looctd¢ Aartabaye . Quay LocatdTte rable tg, = dq. eowartehe > bhile Cig. hasnt 0) £ é Aeconent a. = (ecount) iq snoxt (>; axce- acd Cay ; : \\ § xS or SRNR RAR OAR eee eee ee Baten Apex (a4-83) \. Dobeluction to Gatch Agen 2. Prtmduction t Balchabk interface index mretheck 2. Diffosane. Rakween Ootohate Quciy focadd & Prev fy, Excunph pry 17g AA atch Aeon S. Practical Sconario® 67 Batch Apey 6. Stops to Execuebte Badd Apey + 7. Potabage .CtatePul interac 8, Database alloaGalloes intesfag Gs Govewning Limits 8 Livaitation ta Sotodeckion to Dedkbase - Gutchable Gortext & feyrebvorn ustoes ah hee Batches Batch Apex allows you to define O single Job that cub be bsokein tap into smmanngable Changs, whara ues chune con be Poecescad seperately. Ege DT you need to Trafe Field cpdate of eueseppec de oe Accaunt objeat iy yous Syowi2ation, thon ue howe Qouaesiring Imoits that Loduld weatvct ag em achteuing fhe cebouo tage: Reason + 2 a Single ‘trantaction ke Gun Proce osly (0,000 secosde Noun, be the above Case iP cxehave mere than (0,000 wOCOMS {tra Seprization thon uecan rot paper thie field updale. CateinApert On the GatchApex it will fetch all the. sedis on Udhich You. Want to Pesfornn the field update ard divide ther Unto ligt of S6@ vecords and on eueny 200 recog operation ig syed Sofewateliy. > This would hap us fo execute on mow tha lord tecdde ag ,it Wort Pasfdim an opation oo all the weeds a gine tearsaction insteod it diuiding ther into Mo. of ae tages edhese Cach cubtoste wrap Contain the reonels upto 2000 « Datorbose. Batchable Mteaface + TO we the BatchApex concept tha Apex clas: Showld trnplement Database. Badchable ttusface. € —> Potobar. Gatchabe wtesface Consicte of NUE be lyplemmented . “ ( Stastt » matPod \ 2-Cxecute method. arstormaticalley called of the I Staust matted *— & begining of the Me . thie fs socow Gb objects on Which the “uy pasborred. =D Thic seconds BHO broken down into Sub take cund given to execute wnetied: . Cyntax | geval (Patahaso. Gueraylocotd |Ltewble ccoblock S > Stast (Database. RaitchableContent bed & “ AAR RRA RR eR Ree ee ee as Me — the sabuen type of tie Stowt rnethad coy te “) Daterhage: Guarsyfocatsd ey ‘t) Dtewable Database. Quesylocatd fae tae Database. Quaeyytocatdy Gs Belew type to theStaxt mathod cahan yout on fotching the wecosls ating A. Simple sylact qeamagy, NOEL the qatetning lomit Says YD etal verebug of weds vetsiarted sby coaLduosieg $0,000 . D tal vernbes, of vecords wobsieusd by ° (0,000. Patohar *Ruinridocatd) Bub, in the Batch Apen the governing Linntts 5 cea qpeonayyaaee bypased ard cee can feich cepty somilon secords eaing Caiabase. Quasylocatd ; : Excunplay’ Global Patabase Quasylocate) Stors-Catabow otchable@yntext be) ‘Bek Dactabase. get Quarrylocatdi( ‘select (reume from Accowne'); y EQOe yanite 2 Stost wrethad to fetch all curstornar wame , AcooantTyee f-som Cregtornad Object hose AccceomtType iS ‘Sautry’. Qlobal Database, Quasylocatd Stast Database .Batchable Context be) f Steing cal = ‘select td, Custorees.rome. $ Prony Cuuctormeg¢ hag Ac 4 WD Mesable use ‘te a hen You Vat to age Comnplex lage 8g gt the voeorde fo the batch job: ‘ > Eq? global cl x. towable LO alcbal ‘tte acAccount > tant Dadabow .Aatehable context bey & sett TON WegTERELD I Thig gheukd veka chiect of the _ Chay that has ioplerronted y ‘itewde interface > a o Re n ie ay ee ee ee ee ee le eo Tae D execute raekhod *- tthe wcords cahich ada fecthed from tha Stat methed 022 Atwided into batches of 200 weeps Cach. Neco Choxy ote of 200 vecoats axe P Seperately pass to the execute method Sepesakely aind th operation chat cn Laant to peahding ON thos wocetle Gk Bal weittern im thie Cxecute Vhattiod, Syntax Global uoid execute (Palobase « RatchakeGontext: 6, Listep ad § this Trethad fakes tun pasaimatege. : >A vefewence to the Dotichare./Gatctabeganteat Obiecs > A ict of cobjacts cach ay Ket, ow a ligt of - Parsonatesized typed Le, Sekt of 200 wewads ewhich ade passed FO the execute Mmathad ase stowd in tris fist. 3) finisty ‘mathed + Jthon the Staxt raathod has fetched (00 tecovds on which UR want to feastdin the -ofexations thoy ax divided int © bateh€/Gwoups off Si2e 200. > On wtesy batch A the qvoup the execute vmethed is calle, > Which Toons execute method is called 5 tre. — Abts, @ Cxocerting emery group|boteh the govesning lunite am seset fos the exocate ¢ method. — > once all the batches asa executed thon finigh Method call be Called to send arcail watifintion d {cttyoct &xcition 0st: we o Syotour + ~ total uoid finish Cratobases texP ac )f 3 Note t- All the 3 wmtthede intasface wefesys to Database. er Cyl | nic Object 16 “ued fo track the proge job. Exovople| p - progsam to update. Accunt Name woeh Oblect eoith Sei Mb. het the fecountrcaree - a Aa ExQuaphl'r Lipite Q batch apex progiary to Update Account nerne to the Account Obiect with safe tmp! belle the Accomnt name. global class Account@atch mplerments Datobave Baktatle Lobfect> g Global Databare-Quessyfocatd Start(Dotahase. RotetiableGentexct { " Stsiog peng = ‘Select td, name froin Aecoune’ detwsy) Database, gotaunay! oon Quay); Global void execute COatatage, BotchableCoptext be, Littek Account > ope 5) List< Accum > ate = ney List< Accacint >C): ae $8 (Account a! acc) G. Marne ={utbs.!taename ; Gce-addced;, Update acc; 4 gical ucid Ptnish(Catahase, Garchabl Gonteat be) ie & & Example 2 '~ Lumite. a batch apex Program to phone no. i tio Gokack obiect with the phono no. in the Covrenp ing Account: @byeck- tthasa Contact i¢ a child of Accouy » Jlobal clas contadopdote 7 mh Jocechject S g Global, Datohage -GuassyLocatd) e-Calchoblecrvte-be) £ Shing qpasy = ' r (Account. phone fren SS Contanct'; : glocatd Cqusesy); (Cotabare. GetchableContext be , * Hist sGontace> ope) Lict Con = non List C » FerCcontoct ¢:con) £ RRR RRR AR RRR AA RAR AAR eee ee AB © pho = c- Account: phore.; Con-add(c); 5 update Con; & - Global void finishCpatnbase. Batchable context te) g . 5 \ 3 +) How to_tnwoke hakchaper Job (8) hero to eweede tne hatch Apex dob programmatically - Wa can use Databos-eicetiteBateb() rnethad to proganmatiolly begin the batch teb. Syntew- public Static OD esecuteBaich(Sobiect dastnayne) Public Stoke Tp cxeceteRatchCcobiect clasgname, Mtoges scope) —d ‘The Ahove tio Tretheds ase Static methede — Of patabage Class. te coy Ue any ore of the Teethad to Occute the. Batch job: NOTE "= ‘tha clag rane phat ar aia passing to the Datokare exceuiefateh srmetiiad Should be Obiect of the chsg Gobich bos, implernented Cokabase. RatehaHe i ntexshexce crs of eatcution of Bach Apex ‘ob tahen x tre through Database-executeratcrot— Qf Sept: cweate A Object FB the Class Patobase Ratchable tmtesface. tepair Laheo add the batch 4 2P4E ovre wo te anatlable tm the qeenten achornodtioll y Cantey method Bill bo Tucked and till collect all the socom enlobich wel We. Teed! to peufotm the opevation, ne Re BARRA RARARARABRARAARAR EA BEARER EDA MepsS! ne the weconds that ase Fetched Fearn the Stout salted Ox diuided IHto Serall Group (batch Of Sie giwen iD the | Datobhage . arecutennetiad « NOTE Th case fF you don't Specify the Size bop dofoult TH tafeg 200. Sepos on cuexy batch of vecosds exceute matted owl be. ouoted « Step7 | One.all the batches ase executed thon finiah Ynathed cll be alld. oo NOTE 1) fakobase- execute rmathed 16 going to sekumr id ef the bates job. using ceich Got. can rrontS Id abost the Opesakion - &) Al the axynchwemees tobe axe Mtored to ‘ AsgncAPexatab ‘ obleck from thic Car Caw srnemitor no ot Jobs procssed s Ou aayrchworony Jb and Cates of the Jos . Excumple + Dp hokchpecessid = Patabaw erecuteBatch Ceassiqn) ; feyneApextob aa =[select id, Status , obPteme proceed} from Agync Apetob Where nu) =i batchprocesticl J 5 LETUBTO \- Ceeote a yisualffea page with Dnpat text button. &. When tex click on the Replace batten iw the Cuutom Viceualfekea Page. 3. Fetch ALI the. seconds ‘on the Customes, obiect dotth the Cugtomas YIM vratching qith Yarn Given eo Page . 4. update tris, Account Type ag ‘Saving! Stopi s cecare G batchiper clags gp cP the Account Tyee ¥ Alowal lags Gistorneny fy Joeman? batatase. Batchabla qleral Daterbaze Quesylocatg] Stost Coatabaye . Bakababk conte ‘ 8c) ae a a ee eee ABR eke) Dotobere .qetauciay locates C' solact id, Acoount Type, fsorn Account cohese Wame = ‘prey Narre) . Y Glotad void execute (Catahaw . Bakchablecantert be , Est CCustomas__¢ > Scope ) Bist Cuat snes List < Cestomag_ ic > 0) j fN(custornayy cc cust) C. Accocunt Type ¢ = ‘satin! Ctrgt add cy Bg Update cust 5 & global void -Rnish C Database. GatchaHe don text be g Neaaging, angle Erno] vessage renygumnat| =7Oh wexgaging « SrpfoErmotlMexrage C) ; Sbingr 3 toatl = roy Stringe 3 # abc@greail com}; veqorrail ack HA re90g Ctoadd ) gern. get Subicct C' Gadehpaocessed rayernatl: aetplointoteedy("@atch Completed Succopsfeally '), Newsaging. cord Erroll Cnen Ucgtaging . Ernaild) £ myermnl a; 5 a O Step2 Create Aper clos to'mvoke. a Ee peblic class TostMybatch b f ° Pubte Steing en Z get 5 Pulte PoaeRefe ) x “tee = Ten CustomnaaBatch rome), id= 1° CxeculeRatch Conybeutch , 400)» rdsbug Hy job id 4 1d); & StOp3 Create A wisualfdce page fo cal tre TeatMybatch clog TAR ROR RR RR RMR RAR ROR RR ee has 3\ Saper:ourpattabal > Entey nome Sapex: wypukTedt Volew = “8 { mgnamed'/s Serpex spage> ‘ : Dodtalage. Stotefat ————— Each execetion of batch apex Job is Contidarad ag discrete. toaniaction. Wbich mmeang when gou haue a batch job with (oo Yocorsds Cxecedecl coith “optional Scope of Qt Becosds than |) 5 batty Gakehl —> 1-200 Batehs —5 201-neo Batchs —s dot-600 =} hathon taecall exectete on bptch1 to Summmari2e tho valiea boteges Sum =p; Public void excceete. @atabar +Bakchahe @ntext be jit Account sare) g ta (Account a+ ope) Sum = Sum a. Annual Rerenue ; 3 spree Rote of (200 Teco callthy execake mathed | With 2ormcorde Cofose calling eaccutec) + Sun =0 Aptos, caltiyg execedk® CD > Seon 90000 (cssuane it) —> tren the executec) is alled en kateh2 of vecdds 201-Hoo thay Titial valus_of eux again set to 2250 | aetde calling executor ) On Batch} 21- SO” Attes, calling exeastec) op Rotehi 5! 9) = 30000 + Sumn=somn0 hath wx call exocecte (yy Gn Gat SS First Sk = again « Sur=0 | thon aghin froxh yoo use coleculated agetn > Lohich Years, tbe! mS fornonded from one eXAcute C) to eC), taint -Stadoful “tn the Clax definition vy) State across these transactions . this is Ustat 4) counting dh Semmarizing %cords ag they ore Drecessed. FAN G7, SEPPEEC YoU Sob Prowased cppostanity “Decords - you cbuld define a Trathod iM execute, to aggregate HRM AAA ERA PARRA RAR AA ARRON HA Bd FB totals of tro Oppostunity Ormmcents Qs thay cats processed, global clay Summmoasi2e Accocent Total implements Dotabue , Botchale Database Stoto-fug 8 gical Final Stang quany ; global, “rte geo, Saommany ; global Semmanire Account Total Geving q) & Quooy =g ; Summa y =0; 4 Global Datahate Guasylocats Staxt (dotahne, stehablecantodt &) f Petusy (Pakakase, gotQuary Locatd Geasy) glomd wed Goceto Coatahnge. Bachabe Corstay By, HSt (0 calleuts crecede — 10% 5=50 callous finisb¢) —> tocalloute Fo Glloats in entive operations Limitations '- —> wetheds daclased ag futuse axe n't allowed ‘tr the elassed that bplement Database. Botchable ‘intesface. > Mothate daclased as futuse can't he called for Batch Apex chek. —> Fd shasing Gre caluctlation, ne wecornmand that the exoceite vastheact delete and thay re-Ceeate'all Apex nanaupe showy 48 the vecords ‘tm the bate » > Peach (6000 Arynchpexrdd seconds Apex Cvoater one adiitional AsyneApextob tecord OF type BatchApexrNOskey 463, Totegral U2e. Schepue Apex (64-98) Ts Brtveduction fo Schectelable Ape 2. Metheds in Datesbage.Achedulable tntesface 3. Schacwlable Apex Esarnglas ue Creaking Tine Pale S- Executing the Schedulable Apex. & Gouusning Kaos . F Realtime Sconariog SNR ANN ee AAR RRR RAR AR AR RA Re ne ne oh 48 Preex Softee :— TE will TMuokes the Apex clasg to sw at specific Lory, Anytaty wko coant to schadule theis clase thoy have to troplomant Schadulable intesface Schedulable ‘mtesface “the clas that “‘rimplements this, ‘wtastam don be Schadabed to sun at diftesont ‘Mtemvale . This tntestac has, seuasol method thoy ase fuble veld oxabe Cechalalbbagie Oe) Be public coax Mysehedeslo “woplerrente schedulable g public oid exectele (GhedulablGantoxt sc) £ Account 0 STR Account(Name = ‘pawa2) SINRESE O ; & iy —5 The Schidulos, call su i systerncrntoxt, Ahich meang all tho closes asa exccetted Libethads the aged hag Prarriseiqn Pnot- > Re GH THovitor oD Sop te caccution of Sehedeeled apex ited using Solespoce Legg inteaface 4oorn setup. kauigation Latup 2 Honitoving > Tobs —3 Schedulsdvobe the exacted) ‘nothod must bo declared aq public & gloral. > Using Syrterm Ccheceda ~Sygtern. schedule one you cae inplemnnted schiluleble Yo Lyrtomn. schaddable mnathad to Syston »Schaduloc y raethed e U name Of the job. 2) Expsosion that © cau sarerent time anddote of the ® A eX: fou want to exccuke > Expressinff TS tea Foor of Seconds, ™irates , hows ory th , ke onth clay of the Neck, © ptional yeous > teocende Min HOUTS DAY-NOPth Month OAY-Weefc optivsal yeas, | (4 Cposation . 8) the object of 7 Rm mR RRR RRR Re eee 0-60 of OH 1-3! tho Special chasacterss oS 6 Specifics MO Specife valu. thig is only aualatle f& chosy of ths mmorkh ard day of the. weak EQl- Wvite the exprerion fo Schedule ary opesotion oth of Auguet at 12:30 PH. Ant fo a0 (2 16 8 2! Lo ao 12 Io ae 2 *o 80 12 to fq 2 21d", Eqs. Wivite an XxPreyion tO Schedele aun opesation on Yon Monday [2180 , fg ‘0 80 12 2 Mon! fOueo ae ae ES Spocitieg all tho valea. Eqr tavite the expregion to schedule an opesction on evesy dary of the ALG at [2'30 py ‘9 26.12 # Ava 2' ‘9 80 (2 & B 8! EQ Expsession to schedule om auesy hoo on (oth AdG ‘9 & O82! Lor Gpeetfies the end of the wange. this is availabe only day Of the month S) chap Of tho Wek . Egy bivite an expseszion to echedub the opewation on Laat friday of the Mawrch at 0120, XS" © the ‘0 2 10 2? 8 all. LW & epocifies reasust Week clay of the gi is sodursdasy auailarh fd only ayy of He ‘north. i EQr DP co Specifies sont aud 20th j Cas sang on iqth I i give v then it Buns on mogday ‘sot fous Ynonth, Egr bivite an expseyion Quy Opesation on nee.s034 ® Hy tatecteclayp OP Sos} 5120, ‘0 2 eS eR dking chay of lagt week dow of TES chic specifies wth day of te month, Weck Day ft Cay Month QHD TH will Te Yondax of COSY ond month. HN RN mR RN AR RR RR RR RK ee es J TAN MAR “eeONs TAN-MAR, Bb to > Bh you veant to schadube aye opesation tor have to Cseate, an obiect foo toe Clase Which bas impbrmented feb Schederlakle ‘iwitessface . Class MySchsdula ‘implements Schedulable 8 public wold exocute ckadulable Gntext 8c) g 4 & MepSchodulo ny = Ph MySchadalot ); Stoiry ts = ‘00 0 %3 oY) Lystom : schedule, “onyaos SB, my) 3 u od No tixma — Obieck fdnrat Sitter scbadulaBateh¢ >t System: tchedleBaiche) (8 ead to tuna schedule a Boteh jobs only ore tha fduwe Hime. thie Thethod bag gor @ 8 Pasametess. Podarnt - Dnatame of a class that tnplomnunts Database Batchabla tntesface. FosamM2— Job name- FAmAMS - Toe Tstasval ages eohich the Job Should tasit exocuta. Pasam$:~ Dea an optional parometes cobteh t] define, the Tha system: ScheduleBatch ¢) vets > Td (Goon Priggus id) : . ‘No.of that processed Ab a tirne - —> We cou une the ob Td to Exaunple 2— you have to firstisi tha Schedulable tteuface fs tra class the Spectty® the Ss , chadbe Ape: a Aron class = a. “ang Systemeebadila rota, Qlobol chsg pI Bo [, Scheduloble £ global. (schedulableGontext sc) LSE acc = AcBrynt > S * ae oct eae cewunt @ = Cece . SS 5 Global void firta, (database. Batchable ented 6 ¢) ON A RO ma Rae ee ee en yy x 83 iy gloat clas. MySchadale Umoplemonts echadelable & global void execute (chedalableContext sc) e : MyPatch mab = mew MyBatch ¢) Database. execute (wb), 5 3 Veotlotor class Taxtechadale £ public PageRefosarnce ¢hewc> g String Hmefsame ='0 © 8 © * ? o Myschededs Tag = Tew M )- Syston. Shedule Crngsob', trvrefsarne (mS) | ¥ a VE rage apex form > ‘St sheen}! /> Sfopacfosims N [apex:page> Schrdulable Apex imitations D> bWecan Schedule Gully (00 Jobs ak a time. 2 Moa. Of Apex schedele Jobs mn an howe is 2,560,000 mpurmbes, of Jobs. > Syrebrorcug heb casvice Callow axe not Ceppovted ty Sehtdulable Apex: / Ld Se CU TN AR RRR RR Re me RR OR ee ee w BENED SOFTWARE Ce ZB Real Time Senario’s and UseCases Real Time Senaraio 1: Database.Stateful Interface Thave batch apex code updating two fields in Opportunity line Item(OLD. While I run the code for complete batch the values in the field are updating correctly. However, If I spilt the batch apex in two or many, I am facing the issue of the last batch value getting updated in Opportunity line item instead of complete one. for ex:- Consider 3 record of value 50 each, | am expecting the field in OL to be updated by 150) and it is updating rightly while I run the batch for Database.executeBatch(job,3): where as if | split the same as Database.executeBatch(job,2); then the field is getting updated by 50 instead of 150 global class SummarizeAccountTotal implements Database.Batchable, Database.State ful global final String query; global Map accountmap; global SummarizeAccountTotal(){ accountmap = new Map ops = (List)scope; Bened Software (P) Ltd, 8-3-219/1, ath Floor, DTDC Opp Building, Near Saradhi Studio, Ameerpet Ph; +91-40-66781355/56 training@benedsoft.com www.benedsoft.com BENED SOFTWARE sales for (Opportunity 0 : ops) { if (accountmap.containskey(o.Accountld)) { Account a= accountmap.get(0.Accountld); a.Test_Amount__c += 0.Amount; accountmap.put(o.Accountld, a); UY elsef accountmap put(o.Accountld, new Account (Id = o.Accountld, Test_Amount_¢ = 0.Amount)) global void finish(Database.BatchableContext BC){ uy! update accountmap. values(); } catch (Exception Ex) { system.debug(Ex}; } Bened Software (P) Ltd, 8-3-219/1, 4th Floor, DTDC Opp Building, Near Saradhi Studio, Ameerpet Ph; #91-40-66781355/56 training@benedsoft.com www.benedsoft.com B BENED SOFTWARE ree Allow Callout interface Senario with example I had to integrate a client’s Salesforce and NetSuite System. The requirement was to implement a web-service that synchronises the financial-data between two systems everyday. In dev terms, the client’s Salesforce has to make a GET request to the NetSuite System, parse the returned JSON response and save the data in respective Salesforce fields. When I looked into this, | found there was an Apex Governor Limit of 10 HTTP callouts in any context, i.e., you cannot make more than 10 HTTP request in one session. For the current requirement, I had to make around 3500 calls a day. So after a lot of digging, 1 figured owt that the workaround to this problem is-usi Apex and implementing HTTP requests inside the same. Batch Apex was introduced to empower the developers to be able to build complex, long-running processes on the Force.com platform. By inserting the HTTP request in the same and it works like a background web-service that runs asynchronously and needs no supervision. Sounds sweet, right?? So let's get started. To use batch Apex, you must write an Apex class that implements the Salesforce-provided interface Database. Batchable, and then invoke the class programmatically. In order to make the callouts, you also have to include Database. AllowsCallouts in class definition, Let us first ereate an Apex class the implements Database. Batchable andDatabase. Allow Callouts global class BatchSyne implements Database.Batchable, Database.AllowsCallouts { public String query = ‘Select ID, Name from Account’; global Database. QueryLocator start(Database.BatchableContext BC) { return Database. getQueryLocator(query); } global void execute(Database.BatchableContext BC, List records) { String endpoint, for (integer i try { HupRequest req = new HttpRequest() HttpResponse res = new HttpResponse(); Hip http = new Http(); ), i< records.size(); i++ ){ Bened Software (P) Ltd, 8-3-219/1, 4th Floor, DTDC Opp Building, Near Saradhi Studio, Ameerpet Ph: +91-40-66781355/56 training@benedsoft.com www.benedsoft.com & BENED SOFTWARE sale com Drive for Exeller 17 Set values to Params endpoint = "Your endpoint, eq,setHeader('Authorization’, header); ¥eq,setHeader('Content-Type’,‘application/json’); req,setEndpoint(endpoint); req.setMethod("POST’): req.setBody("Inlormation you wanna send’); req.seiCompressed(true): // This is imp according to SF, but please check if / the webservice accepts the info. Mine did not :P 11 Had to set it to false if ((Test.isRunningTest() { res = http.send(req); String sJson = res.getBody(): System .debug(’Sir + res.getBody()); } // now do what u want to with response. } catch (Exception e) { System debug('Error’ + e.getMessage() + ‘LN: + e.getLineNumber() ); global void finish(Database.BatchableContext BC){ /Jyou can also do some after-the-job-finishes work here } You can query any valid SF sObject in Database. QueryLocator. In this example, you can use the records Account object to use any data-field from Accounts and even perform DML operations. Now. to execute the above Batch Job programatically, you need to use Database.cxccuteBatch method. The Databuse.executeBatch method takes two parameters: An instance of a class that implements the Database.executeBatch interface. The Database.executeBatch method takes an optional parameter scope. This parameter specifies the number of records that should be passed into the executemethod. Use this parameter when you have many operations for each record being passed in and are running into governor limits. Bened Software (P) Ltd, 8-3-219/1, 4th Floor, DTOC Opp Building, Near Saradhi Studio, Ameerpet Ph: +91-40-66781355/56 training@benedsoft.com www.benedsoft.com Q\ BENED SOFTWARE rce vt tor Exe Test Class: @isTest public with sharing class TestBatehSyne { st testmethod void ml) { List(); for(integer i = 0; i<10; i++){ Account a = new Account(Name: acens.add(a); 3 Test.StartTest(); insert acens; BatchSync syne = new BatchSync(); syne.query = 'Select ID, Name from Account’; ID batchprocessid = Database.executeBatch(sync); Test.StopTest(); t G@isTest private class TestScheduleSync { static testmethod void testSyne() { Test.StartTest(); List acens = new List(); forinteger i = 0; i<10; i++){ Account a = new Account(Name='testAccount'+'i') acens.add(a); String CRON_EXP = "00.23 **?; insert accns; scheduleDailySyne syne = new scheduleDailySyne(); 11 Schedule the test job String jobld = System.schedule(‘testBasieScheduledApex’, CRON_EXP,syne); Bened Software (P) Ltd, 8-3-219/1, 4th Floor, DTDC Opp Building, Near Saradhi Studio, Ameerpet Ph: +91-40-66781355/56 training@benedsoft.com www.benedsoft.com 3B BENED SOFTWARE sale force om Drive for Exellence (/ Get the information from the CronTrigger API object CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobld); 11 Verify the expressions are the same System.assertEquals(CRON_EXP, ct.CronExpression); System,assertEquals(0, ct.TimesTriggered); System.assertEquals('2022-09-03 00:00:00", String. valueOf(ct.NextFireTime)); Test StopTest() } Real Time scenario where you can use Batch apex: Business Use Case 1 : We use batch apex for bulk processing. Let's say you want to update thousands to accounts on a regular basis or (even if just one time) and real time update is not a MUST HAVE requirement You know how you are bound by govemor limits for all the retrievals , updates , inserts. Batch class has much wider governor limits . Its an async operation and you ean run a nightliy job and process all these records without hitting limits. Examples : Tused batch class for a scenario where I had to send email to all contract owners 15 days before payment due date, There were thousands of contracts nad at one time there could be many contract owners meeting this criteria. Also, apart from sending email ,I had to update a flag on contract. So, I schedules a daily nightly batch job for this. Business Use Case 2: An organization's sales team is using Salesforce CRM primarily to manage their Leads, Contacts, and opportunities. This is akin to a retail setting whereby there are multiple physical locations and each location has its own sales team and sales manager (think ear dealership). In this setting, Leads (and/or Contacts) enter through multiple channels such as internet marketing, phone calls, walking through the front door, etc and are assigned to a sales rep based on a round- robin format. That sales rep becomes the owner of the Lead, but only has protection for a certain period of time before the Lead is redistributed. Bened Software (P) Ltd, 8-3-219/1, ath Floar, DTDC Opp Building, Near Saradhi Studio, Ameerpet Ph: +91-40-66781355/S6 training@benedsoft.com www.benedsoft.com zg BENED SOFTWARE ce Drive for Exellence The protected period of time is based on the sales rep’s last activity to the Lead/Contact. In other words, if the rep is not actively working the Lead/Contact then they lose protection, and if that Lead/Contact ends up buying a product then the rep will not be credited for the commission. The question then became, how can we automate this process of removing Lead protection based on the sales rep’s activity? One of the great features of working with the Force.com platform is that there are always multiple ways to solve these types of problems. And these are good problems to solve because the solutions free up people's time and help advance business. In this situation, the basic design for this scenario is that when the number of days since the last activity is greater than 5 days, revert the ownership of the Lead’Contaet trom the sales rep to the sales manager. This lets the sales manager redistribute the Lead/Contact to another sales rep. The first step was to create a new formula field that retums a Number and call it Days_Since_ Last_Activity. The formula is this: Today() ~ LastActivityDate. At this point, you might think about creating a Workflow Rule that says when Days_Since_Last_Activity is greater or equal to 5 then Update the Owner field. However, a Workflow Rule is only fired under three circumstances: a)Only when a record is created; b) Every time a record is created or edited or: ¢) When a record is edited and did not previously meet the criteria, This means that the workflow rule won't get fired until the record gets edited, and we want the ownership to change immediately upon the passing of the protected period regardless of whether or not someone edits the record. The solution in this case is to use Batch Apex to query the database for all Leads/Contacts (we use Contacts in the example code) that have crossed the protected period, ie. the Days_Since_Last_Activity fields is greater than 5. Then, we reassign ownership to the correct sales manager based on which physical location this Contact is associated with. Next, we create ‘anew Task associated with this Contact so that the Days Since_Last_Activity gets reset. Lastly. we schedule this Batch Apex to run each might so that the ownership is being recalculated ont daily basis. Below are the Apex and Test Classes that make this work. global class UpdateAllContacts implements Database. Batchable 3"; global database.queryLocator start(Database.BatchableContext BC) { retum database. getQueryLocator(query); } /Iclose start method global void execute(Database.BatchableContext BC, list scope) { List » Task> taskList = new List(); (/ Iterate through the whole query of Contacts and transfer ownership based on the location. (7 This example only has two locations. 1/ Create a Task that’s associated with each Contact. This resets the Days Since Last Activity formula field for(Contact c : scope) { if c-Location_¢ =~ ‘Location 1’) { ‘XXXXXXXXXXXXXXXX'} new Task(); c.ld tsk ActivityDate tsk Status = 'Complet isk.Subject = ‘Ownership Transferred’: stem.today(); task List.addlisk): } //close if statement XXXXXXXXXXXXXXX", yew Task(); tsk. Whol Ad; tsk ActivityDate = System.today(); tsk Status = ‘Completed’; tsk.Subject = ‘Ownership Transferred’, taskList.add(tsk); } “close else close for-loop try | insert taskList; } catch (system.dmlexception e) { System.debug('Tasks not inserted: ' + e); y Bened Software (P) Ltd, 8-3-219/1, 4th Floor, DTDC Opp Building, Near Saradhi Studio, Ameerpet Ph: +91-40-66781355/56 training@benedsoft.com www.benedsoft.com J BENED SOFTWARE a force _Drive for Exellence try { update scope; } catch (system.dmlexception e) { System.debug('Scope not updated: * + e) t } /Iclose execute method global void finish(Database.BatchableContext BC) { AsyncApexJob a = [Select Id, Status, NumberOfErrors, JobltemsProcessed, Totallobltems, CreatedBy.Email from AsyncApexJob where Id = ‘BC.getJobld(]; I Create and send an email with the results of the batch. Messaging. SingleEmailMessage mail = new Messaging. SingleEmailMessage(); mail.setToAddresses(new String] {a.CreatedBy. Email mail.setReplyTo(’batch(mycompany.com’): mail.setSenderDisplayName('Batch Processing’); mail.setSubject('Contact Update ' + a.Status); mail.setPlainTextBody('The batch apex job processed ' + a.TotalJobltems + * batches with + a.NumberofErrors + failures.’ Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } Uiclose finish method } Hiclose class Apex Class Used to Schedule the Batch Apex Cla global class ScheduleUpdateContacts implements Schedulable { global void execute(SchedulableContext SC) { UpdateAllContacts uac = new UpdateAllContacts(); database.executebatch(uac); } HWelose execute method } Miclo @isTest Bened Software (P) Ltd, 8-3-219/1, 4th Floor, DTDC Opp Building, Near Saradhi Studio, Ameerpet Ph: +91-40-66781355/56 (1 aintinig@benedsoft.com www.benedsoft. com 3B BENED SOFTWARE lore Drive for Exellence private class UpdateAlIContactsTest { static testMethod void TestUpdateAtiContacts() | (/ User Id's for the two sales managers. String ald = "XXXXXXXXXXXXXXXX}} String bld = 'XXXXXXXXXXXXXXXX' List contacts = new List (); List tasks = new List (); Test StartTest(); // Create 50 Contacts and assign them to the sales manager of the opposite location. for (integer i=0; i<50; i++) { Contact ¢ ~ new Contact(FirstName=Test’, LastName='Contact’+ i, Location__¢ = ‘Location I’, Ownerld = bid); contacts.add(c); } Hiclose for-loop 1/ Create 50 more Contacts and assign them to the sales manager of the opposite location. ries iSO: i++) | Contact ¢ © new Contact(FirstName="Test’, LastName='Contaet’ + i + i, Location_c = ‘Location 2", Ownerid = ald); contacts.add(c); { Melose for-loop insert contacts; List cont = [Select ID, FirstName from Contact Where FirstName=:Test' limit 200); 1 Create a Task for each Contact that was just inserted. Set the date of the 1ask so that it will set the Last Activity Date to a date older than your protection period. for (Integer i=0; i<100; i++) { Task tsk = new Task(); tsk, Whold = cont.get(i).td; tsk. ActivityDate = System.today() - 15: Bened Software (P) Ltd, &-3-219/1, 4th Floor, DDC Opp Building, Near Saradhi Studio, Ameerpet Ph; #91-40-66781355/56 training@benedsoft.com www. benedsoft.com J BENED SOFTWARE Drive for Exellence tsk Status = ‘Completed’; tsk Subject = 'Test Subject’; tasks.add(tsk); } //-close for-loop try { insert tasks; } catch (System.DMLexception e) { System.debug("Task List not inserted: ' + e); 3 // Call the Batch Apex method. UpdateAllContacts uac = new UpdateAllContacts(); ID batchprocessid = Database.executeBatch(uac); Test.StopTest(), AsyncApexlob asyne = [Select Id, Status. NumberOfErrors. JobltemsProcessed TotalJobltems from AsyneApexJob where Id ~ :batchprocessid]: System.debug('Final results are' + async): + System. AssertEquals(asyne. NumberOfErrors, 0); System. AssertEquals([Select count() from Contact Where Ownerld=:ald AND FirstName="Test}}, 50); System. AssertEquals([Select count() from Contact Where Ownerld=:bld AND FirstName=Test J, 50); System. AssertEquals({Select count() from Task Where Subject = "Test Subject’], 100); } Wéclose testmethod } Welose Class global class TestScheduledApexFromTestMethod implements Schedulable 1 This test runs a scheduled job at midnight Sept. 3rd. 2022 public static String CRON_EXP = '00 03 9 ? 2022'; global void execute(SchedulableContext ctx) { CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered,NextFireTime FROM CronTrigger WHERE Id = :ctx.getTrigger!d()]; System assertEquals(CRON_EXP, ct.CronExpression); System.assertEquals(0, ct. TimesTriggered); Bened Software (P) Ltd, 8-3-219/1, 4th Floor, DTDC Opp Building, Near Saradhi Studio, Ameerpet Ph; +91-40-86781355/56 training@benedsoft. com www.benedsoft.com ICE. n 3B BENED SOFTWARE sal Drive for Exelience ‘System.assertEquals('2022-09-03 00:08:00, String. valueOf{ct.NextFireTime)); Account a [SELECT Jd, Name FROM Account WHERE Name ‘testScheduled Apex FromTestMethod'}, a.name = ‘testScheduledApexFromTestMethodUpdated’; update a; } } Note : you must guarantee that the trigger won't add more scheduled classes than the 100 that are allowed. Test Class to for schedule Apex: @istest class TestClass | slatig testmethod void test{) { Test.startTest(); ew Account(); iestSchedulec|ApexFromTestMethod’; Account a.Name insert a; / Schedule the test job String jobld = System.schedule(‘testBasicScheduledApex’, TestScheduledApexFromTestMethod.CRON_EXP, new TestScheduled ApexPromTestMethod()); 1 Get the information from the CronTrigger API object, Cron Trigger et = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobld}; // Nerify the expressions are the same SystemassertEquals(TestScheduledApexFromTestMethod.CRON_EXP,ct.CronExpression); 11 Verify the job has not run System.assertEquals(0, ct.TimesTriggered); ‘Verify the next time the job will run. System.assertEquals('2022-09-03 00:00:00" tring, valueOf{ct. NextFireTime)}; System.assertNotEquals('testScheduled ApexFromTestMethodUpdated’, [SELECT id, name FROM account WHERE id = :a.id].name); Test stopTest(); Bened Software (P) Ltd, 8-3-219/1, 4th Floor, DTDC Ogp Building, Near Saradhi Studio, Ameerpet Ph: +91-40-66781355/56 training@benedsoft.com www.benedsoft.com System.assertEquals('testScheduledApexFromTestMethodUpdated’, [SELECT Id, Name FROM Account WHERE Id = :a.Id].Name); To schedule an Apex class to run at regular intervals, first write an Apex class that implements the Salesforce-provided interface Schedulable. The scheduler runs as system: all classes are executed, whether the user has permission to execute the class or not. For more information on setting class permissions, see “Apex Class Security Overview” in the Salesforce online help. To monitor or stop the execution of a scheduled Apex job using the Salesforce user interface, go. to Setup ->Monitoring --> Scheduled Jobs. For more information, see “Monitoring Scheduled Jobs” in the Salesforce online help. ‘The Schedulable interface contains one method that must be implemented, execute, global void execute(SchedulableContext sc) |} Example: global class scheduled AccountUpdate implements Schedulable { global void execute(SchedulableContext SC) { AccountUpdate ace = new AccountUpdate(‘Description’,’Updated Account’); } } To get details about AccountUpdate Class go to http://www infallibletechie.com/2012/05/batch- apex. html Go to Setup 4 Develop a Apex Classes and then click “Schedule Apex’ button, Bened Software (P) Ltd, 8-3:219/1, 4th Floor, OTOC Opp Bulding, Near Saradhi Studio, Ameerpet Ph: #91-40-66781355/56 training @benedsoft.com www.benedsoft.com 3B BENED SOFTWARE salroe com Drive for Exellence » te Seto ew Gecetomito. tute [amenaetas] seer woe essere sate nike Sa Se EOTAE Pte o spp sess ett tose 3 Dts =] : nae vo ara ae : sete beshan Schedule Apex wen [poco tna Joon20i2 Bened Software (P) Ltd, 8-3-229/1, 4th Floor, DTOC Opp Building, Near Saradhi Studio, Ameerpet Ph: +91-40-66781355/56 training@benedsoft.com www.benedsaft.com BENED SOFTWARE _ Drive for Exellence Figure clearly explains how to schedule Batch Apex. The frequency may be set to Weekly or Monthly. Start and End dates are important, Preferred Start Time is also important: The job will be sent to Apex Job queue. The preferred Start Time won't be the exact time because it depends upon the job queue, The job will be executed aller other jobs in the job queue have been executed. Once you've successfully saved your Apex Classes go to Setup -> Develop -> Apex Classes —> Schedule Apex. Use the class above that implements the Schedulable interface and select the frequency that you want the class to run Batch Apex Governor Limits Keep in mind the following governor limits for batch Apex: + Upto five queued or active batch jobs are allowed for Apex. + The maximum number of batch Apex method executions per a 24-hour period is 250,000 or the number of user licenses in your organization multiplied by 200, whichever is greater: + The batch Apexstart method can have up to 15 query cursors open at a time per user. + A maximum of 50 million records can be returned in the Database.QueryLocator object. If more than 50 million records are returned, the batch job is immediately terminated and marked as Failed. + Ifthe start method of the batch class returns a QueryLocator. 1 of Database.executeBatch can have a maximum value of 2,000. + of Database.executeBatch, Salesforce chunks the records retumed by the startmethod into batches of 200, and then passes each batch to the execute method. Apex governor limits are reset for each execution of execute. optional scope parameter + The start, execute, and finish methods can implement up to 10 callouts each + Only one batch Apex job's start method can run at a time in an organization. Batch jobs that haven't started yet remain in the queue until they're started. Note that this limit doesn’t cause any batch job to fail and execute methods of batch Apex jobs still run in parallel if more than one job is running. Bened Software (P) Ltd, 8-3-219/1, ath Floor, DTDC Opp Building, Near Saradhi studio, Ameerpet Ph: +91-€0-66781355/56 training@benedsoft.com www benedsoft.com

You might also like