Crash course on Apex Triggers Salesforce | Complete guide with Real time scenarios

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi everyone my name is srikant today we are going to learn about apex triggers this is like a crash course on epic stickers with real time scenarios and interview questions by end of this video you will be able to understand what is sugar when and where to use triggers you will also understand the use cases of the triggers and you will be able to choose before or after trigger for any given scenario we'll also see if some best practices avail writing a trigger you will understand all these things with real time scenarios and will have some quiz and android questions too before going ahead i wanted to make things clear each took us difficult to learn of course not so the expectation is triggers are very much ferocious like this but in reality they are just like toys you can really play with triggers once you understand the basics you can write any complex logics by using triggers let's understand the definition of epic trigger apex trigger is nothing but a block of code so the in that block of code you can write any of these logics sending of mails creation of any other records doing the callouts deletion of any other records or it can be any any action here and it can be any other action also whenever a record is created whenever a record is updated or whenever a record is deleted or whenever a record is undeleted if you want to do some action if you want to write some action just write that action or write that code in apex triggers or there will be automatically called so whenever record is created you want to write some action do that in a big sticker whenever a record is updated you want to write some any of these actions or any of the complex action write that in apex trigger and that will be called automatically same with delete same with undelete in a single sentence whenever a dml operation happens if you want to perform any of these actions or any of the complex operations then write that logic in epic stickers dot wait wait wait all these things can be done by flows process builders workflows then why do we need to choose epic stickers okay for people who doesn't know him his name is cue boy who usually interrupts the video and asks this kind of questions yeah you're partially true mr cuboid however most of them can be done by flows process builders and workflow however if things are very much complex then only apex triggers can solve those scenarios so the conclusion here is we will create a thumb rule here so if a particular given requirement can be done by point and click tools point and click tools in the sense the automation tools that are provided by salesforce whether it can be workflow rules or process builders flows validation rules duplicate rules etc so if a given requirement is possible with any of these just go for that okay do it with that particular automation tool if it is not possible only if it is not possible only then do it with fx triggers as simple as that so thumb rule one is point and click possibility check so whenever a requirement comes and if you feel epic sticker can do it before that check whether it is possible with point and click pulse if it is not possible only then do it with epic triggers remember this thumb rule because we will be using that in the next coming scenarios trigger logic can be called in below events so what does that mean so you can write your logic and you can make that logic to be ran before the insert of that butler record or after the insert of a particular record or before the update of a record or after the update of a record or before the delete of a record or after the delete of that record or even like after undeletion of that record after unleashed in the sense whenever a record has been restored from recycle bin once it is restored if you want to perform some logic you can write your logic in after delete events same with the other events if you want to write your logic in any of these events it will happen accordingly this is also in entry questions interviews might ask you what are the events in trigger you can just mention all these seven let's take this example so after inserting an account by end user automatically create a contact so we need to write creation of contact logic in trigger so which trigger it should be an insert operation okay insert operation on accounts so trigger has to be returned on account on insert operation and we need to do the action creation of contact okay however the problem here is for insert operation we have two events one is before insert and after insert how you would choose before insert or after insert for a given requirement and the second question is why salesforce has provided two events for a single operation like this so it is being same for update operation also before update and after update how you would choose it you would know to write a logic on update operation but what event that you need to choose before or after same with delete so to understand this we need to understand how salesforce works whenever a record is inserted are updated or deleted let's see before going ahead we need to understand the behind the scenes whenever a record is inserted or updated so let's say we have a user who provides some value in the user interface and clicks on save it will not directly go into the database instead salesforce will make wall tool before it inserts or updates data into the salesforce additionally it will make another world tour after it has been inserted into the database you don't believe me let me show that to you this is the world tour i am talking about whenever user provides the values in the new page form and then clicks on save to insert the record it will not directly go into the database instead it will check if there is any logic written in flow so we have automation tools in salesforce right which are flows workflows and process builders and along with that we also have apex triggers so first it will check if you have written any logic or any kind of thing in flow before insert operation if there is any logic it will execute else it will go to the next step which is apex trigger before insert so if you have written any logic with before insert event it will execute it accordingly if you haven't returned even then it will go to the next step and save into the database once the record is being saved let's say you provide three or four values here and then send this value it will save into the database and it will generate this salesforce id which is the 18 digit id along with that it will also generate created by id created date last modified by id last mode by date so once that is done it will go to the next step where it will check if you have written any logic in after insert event of the apex triggers once the execution is done it will go to the workflow and once this execution workflow is also done it will go to process builder and finally checks the flow after insert event once this is also done finally it comes into the database let's see if there is any issue or if there is any error that complete changes will be rolled back and that particular record will not be saved into the database that's how the order of execution work this is the salesforce order of execution for these events let's say you haven't written any logic so whether you write your logic in this particular blocks or not it doesn't matter poor salesforce will punctually check all the blocks to see if you have written any logic and executes them if there is no logic it will go to the next step so the conclusion here is you can write your logic in before insert or after insert based on the requirement whether it is before or after insert what makes so much difference my job is being done right then why should i bother whether it to keep in before insert or often set very good question let's see that so as the name suggests if before the record is inserted what are the events or what are the things that are there they are come under before events in here flow before insert will come under before even after apex trigger before your insert will also come under before event these things will come under after uh events okay with this understanding now i will teach you how to choose before insert and after insert for a given requirement so here for before insert there are only two rules only two rules i'm telling you again just two rules if you want to pre-populate any field on the same record you need to choose before insert or before update and if you want to throw an error after validating the record let's say if the record is not matching with so and so criteria then if you want to throw an error to the user saying that this is not valid so in that case also you can use before events and rest of any other scenario should go into after insert or after update events okay this is applicable for insert and updated events both and do not try to pre-populate any other objects record let's say if a account is getting inserted you can pre-populate any other field on the same account record but you cannot pre-populate any other record on the same object which which is on account object okay okay let us see what are the things that we can do in after insert event or after update even if you want let's say an account is in certain if you want to update any other objects records you need to go for after uh insert events or after update events if an account is inserted or updated and if you want to do any other action something like sending of emails calling up external system which is call outs or like integrations and if you want to do some something with system fields on the same record like last modified by last modified data record the id created or created by you because these values will not be available before the record is inserted so after that if you want to do some operations with these fields you can do that in after insert or after update event only now let's see what is this no extra dml required so let me explain that with an example let's say you have a friend who is taking this package and wants to deliver it to this destination okay now your house is in between her house and the destination so as anyhow she is taking her package and going to the destination through your home you thought of saving your time and money there so you whenever she is going there you just stopped her and then given your package so that she can take her package and your package and then take it into the destination so what happened here is you saved your time and money as anyhow she's going through your house you just given your package to her so that it is delivered to the destination so finally both the things are done both her task is done and your task is done let's relate this to salesforce so the delivery center understand that as database so this is the database so delivery center is the database so the created record after user clicked on save the created record will go to the database right so understand your friend as the created record by the sales force okay now the before i mean your house or your home wherever you are having your package is before insert trigger or before update trigger okay the package itself is your logic so in this case the created record as i have mentioned in the previous order of execution this created record directly will not go to the database instead it will check if you have written any of your logic in before insert trigger if you have written it will take it and then goes into the database in this way your time and money has been saved in the same way dml operation has been saved by adding your logic in before insert here how dml is safe let's say your friend doesn't take your package and then directly goes to the database so how your package will be delivered then you need to deliver your package yourself which means it will take extra time and effort correct in the same way if you don't write your logic in before insert trigger after the record is inserted if you want to do any logic you need to do another update on that record and then change the values and then save it and it will be another update again or another dml operation again which is extra dml operation so by saving the dml operation you are increasing the system performance with this scenario we have understood that putting our logic in before insert or before update trigger will reduce any extra dml operations so let's create another thumb rule so if we need to update or pre-populate any field on the same record or to fire any validation error validating that record then we need to go for before even which is insert or update in any other condition we need to jump to after event so this is the universal way to decide how to choose before insert or before update or after insert after update this is the biggest thumbnail which you need to remember when writing a trigger scenario number one i have a requirement while user creating an account if user provides billing address but not shipping address write a logic to populate shipping address with billing address how to achieve this so basically what cuba is asking is while user creating an account he will provide values right so in account we have billing address and shipping address if user provides billing address so all these fields are related to billing address so if user provides billing address and doesn't provide shipping address so billing address has to be automatically copied over to shipping address so let me click on save now billing address will be there but not shipping address so user is expecting this automation of billing address to be copied over to shipping address so in this case whenever user is creating an account we need to do this logic so obviously whenever a record is inserted updated or deleted if we want to perform some action we can go ahead with triggers we have other options also which are flows process builders etc but in this scenario particularly we are working on tickets so hence we need to write a trigger here now so trigger has to be written on which object what operation and which even so operation meaning insert update or delete okay so whenever trigger has to be written we need to mention what object is it what operation we are doing and what event it is okay now we need to understand what is the object okay so trigger has to be written on object on which user will do his action okay so whale user is creating an account so basically user is creating an account okay so that's what his action is so based on this action we need to perform this logic so what is the logic populating of billing address to shipping address so this logic we will write in term trigger however we need to mention the object name as account here because user is performing his action on this object okay based on some action we need to do some logic so as per this the object would be account now so if we see we have account now the object has been finalized as account so what operation so operation has to be either insert or update or delete or it is it can be undelete also so in this scenario what should be the trigger option so will again help take help of this thing so where it says the action that user has performed so if you see here whale user is creating an account so basically user is creating an account basically he is inserting an account and then we need to do some action so on insertion which means the operation has to be insertion here so account so object is account and the operation is insert now the thing is which event so before event or after event if you remember in the previous flow chart i was explaining so we have before events and after events also right so which event we have to choose before or after so the event is before or after even can be found by our thumb rule so we have our thumb rule discussed right so let us see that thumb rule now so the thumb rule says if we need to update or pre-populate any fields on the same record or to file an error validating the record then go with before event in any other case go for after events so in our scenario what are we doing we are actually pre-populating shipping address based on billing address so does that come under this scenario of course yes the reason is we are pre-populating any field so in this scenario we are pre-populating shipping field on the same record because whatever account is that that is getting inserted we are updating the shipping address of the same record so as this is the scenario here we need to choose before event okay so the conclusion is we need to write our trigger on account object on insert operation and on before event so as we have all these things we will write trigger now so this is a brand new art people who wants to learn and practice you can follow me along so you can actually do along with me so to create a trigger you can do it from developer console so from developer console you can create any kind of code except for lightning web components lightning web components cannot be done from developer console so to open developer console click on setup and then you should be seeing a developer console option click on that now we will be having a window where we can create the apex trigger so click on this so to create apex trigger you need to click on file and then click on you you see there is an apex trigger option so click on this epix trigger so it will ask you the name and the subject so as we have seen in the previous scenario let me open the notepad so the object has to be account and operation is insert and event is before right so this is for scenario one scenario one this is the conclusion we got it right now so it is asking for us to select this object so as we have seen in the notepad so the object is account so select on account so give some meaningful names usually i will give the object name and the trigger okay so name name shouldn't have spaces in between you can use underscore so i will just use like this so account trigger and then click on submit now trigger has been created so if you see we have trigger name that we have given and the object selection is also given but how does this before insert has come into picture so it's actually a default value that salesforce has given okay so as per our previous conclusion the object has to be account operation has to be insert and event has to be before right so if you see the default value that salesforce has provided for us is very much matching with our event and operation so we'll leave like that okay if your event is after you need to change this to after if your operation is update you need to change it accordingly so this is the syntax how to write a trigger so trigger the trigger name and then account so this is actually given by salesforce itself we haven't done anything even the events are matching with our scenario that's the reason we are not touching it okay so this trigger basically says whenever user creates an account so when it says inserts an account this trigger will be called that one before only so before the record is inserted this trigger will be called okay let us see whether it is getting called or not so to check that we can use debug log okay which is debug statements i'm in trigger please confirm me if i'm getting called okay so how to test this so whenever you write debug log statements you can see once you check it so we will insert a record we'll insert an account and we can see that debug log statements here okay so go to account tab and then click on new just give test123 and then click on save so we created an account so ideally our trigger has to be called automatically so let us see that so if you see here it says we have three deeper clocks so so i will open you need to open all of the g if you're not really sure but as this size is bigger i'm opening this so uh if you have written any debug log statements if you want to see them directly you can just click on debug only by clicking on the check box you are asking salesforce to display only the statements that are in system.peopleblog it says i am sugar at creator credit please confirm if i am getting called of course you are getting called you see this is how trigger is getting called okay now the next step is as trigger is getting called we need to write our logic to pre-populate the shipping address from willingness okay so how we will write it so to understand this so trigger has to so if you need to pre-publish billing errors to shipping address you definitely need that record right only if you have the access to that record you can take the billing address value and then you need to put it in shipping address value okay now as trigger is getting called automatically if trigger has something called context variables okay what is context variables it seems pretty tough no it is not context variables are something like they are nothing but where values or variables which developer needs to write logic yeah if you see what we need at this point of time we need to have access to that record so that we can take the billing errors and then populate it into shipping address so if you see the context variable one is context variable one is trigger dot new okay so trigger dot new is basically a list so if you insert a record if you insert a record that record will be there this trigger dot new trigger dot new will be list of the object that has been defined so this figure dot new will be having account list let's say you inserted one record this list will have one record if you inserted two records from data loader or workbench or some other data loader tool then it distributed you will be having two records if you insert 10 records 10 000 records all that list will be there in this trigger document okay so let us see it's really getting that values or not okay so what we will do is we'll write another system dot d workbook statement so i will just take this out at the regular thread inserted record okay or records so usually we can only insert one record from user interface so obviously this sticker dot you should display only one record okay let us see whether it is working properly so let's go back again and then click on new record test one two three four and then click on save so we have this new record let us see uh so we haven't given much of a details except for account now we haven't given any details right so we'll go back here and then open the latest so these are the latest three out of which this seems to be weaker so i think deeper clock will be there here so you need to check all these three if you're if it is not there in any of the debug logs that you are seeing okay so click on debug log and if you see inserted record and it says account and then it is having many fields all the fields that are controversial in shitty billing state so we haven't given any of the values building city building the state billing post record and we also have the name that we have given test123 and the thing is id is null why id is null it we have inserted the account right so if we go back to the act account that account is having salesforce id salesforce ids can be seen on url right so this id is not populating it here right right equal to null why why is it the reason is this particular trigger is getting called on before insert before the insert itself id will not be generated only after the insert it will be generated let's make if it is before and after i mean let's change from before to after and then save it and then on the same trigger this trigger dot new will be displaying that id value also if we open that that id will be populated with so and so id okay that's how before and after works okay now that we have understood trigger dot new will be having the list of all records that got inserted okay at this point of time only one record inserted that's the reason that list is having one record and if we see building city billing state all the values are empty now so now we have access to billing city of billing state values right so based on that we'll write logic now so let's close this and then i will close this so let's write an if condition first so what is this condition so all the context variables or the variables which needed to the developer will start with trigger okay these are salesforce given context variables okay so it will start with figure only so trigger. is before and trigger dot is insert so basically what it says is if the trigger is getting called on before event and insert then go into this block so why we are rating it already before insert itself says that block will be called automatically right so you will understand why i have written this if condition separately okay but this is no harm right because it says this is true trigger dot is before dependence uh true if it is a before event trigger dot is insert will return true if it is an insert event okay as a record is getting inserted before the insert both of them will be true and this block will be called so this is how it will be started okay so don't worry we'll understand why this block is there now as you have seen this trigger dot new is a list of it's basically a list so even though you record one record or 10 record this will have that list if you insert one record this will have one record okay so that is the reason you definitely need to run a for loop on that list for low so what object is it so the object is account so we will see account record and then trigger dot it's a list okay and then we can write our logic in between so it this particular list will have all the records inserted and we are taking each of the record and then putting into ecc and then this will loop until all the reconsistent but as one record is inserted this loop will be looked only once okay now what we will do is if we need to we need to actually update uh shipping address with billing address correct so acc rec so i will put a debug log statement here in case acc track record and loop okay so far we are good with this loop now the next thing is we need to so we need to update the shipping address with billing address so a c c r e c dot i remember the field name so i will just i'm just giving it okay so we need to populate shipping city with building city right building city acc red dot shipping country equal to ac direct dot building country acc red dot billing postal code okay so now we have our billing address populated to shipping address okay however this this copying of billing address to shipping address has to happen only if these values are empty okay that's the reason you need to mention if conditions everywhere something like if acc rector shipping city not equals to sorry equals to null or empty only then we will have this logic okay the same way this one acc vector we can just copy out and same with this this this okay so as this is misaligned we'll just realign it okay so i will take this paper clock i think this is unnecessary here so it is running through loop of all the requests together you will have the requests that are inserted so list of records that are getting inserted or that got inserted okay okay now it will have the list of records and if shipping address is null then copy that billing address to shipping city and country to country state to state billing to speaking state to building state shipping state billing situations so once this population is done automatically as this is before insert anyhow that record is coming here before it is getting inserted and you updated billing and billing address to shipping address values and it will go back to the database automatic because as it is anyhow going to the database you this trigger will be just called before it is getting into inserted so that is the reason that is the reason anyhow it is going to the database and it came here to prepare to see your logic as your logic is the population once this pre-publishing is done that record will be taken out the database automatically because anyhow that is getting inserted so that is the reason never write insert or update statement in before events because as it is anyhow inserting right so as it is anyhow inserting work you really don't need to insert this this particular account record it's already getting inserted as user clicking on say just before the insert it came here you have shown your logic to pre-populate and then it will go back to database automatically and it will get inserted accordingly so never write insert or update statements in before events you really don't need to update this particular data or like insert the particular data okay so this is how you need to write your before insert let us see whether it is working properly or not okay click on save go back here so we'll create new account test test scenario 1 and then we'll give building street test b1 c1 p1 yes one see okay let's click on save so the expectation is this data has to be copied over to this fields click on save and then click on details and if you scroll and see building state has been copied to shipping street and all the other bills has cropped into that streets according okay so this is how you need to write your logic to populate data from one field to another pillar properly to any fields in the same record so we are done writing the trigger for before insert and for scenario one so in this scenario we learned that trigger dot new is one of the context variable now we also have used trigger dot usb4 and trigger dot ease insert also okay so these are another two context variables now so total in this scenario we have learnt about three context variables so context variables uh trigger thought is before returns boolean returns true if trigger is running on before event okay so same with the insert okay remember these context variables because they are very much handy they will be used a lot in writing trigger so ease after return strip trigger is called when user has done insert operation okay so and then click on save scenario number two i have another requirement while user creating an account if annual revenue provided by user is less than thousand then write a logic to throw an error to user how to achieve this so basically what cuba is asking is whenever account is getting created if the annual revenue so there is annual event so you see annual revenue this is a standard field so if this value is less than thousand then they should provide error saying that annual revenue should not be less than thousand something like that but at this point of time it will allow you to create records with the annual revenue less than thousand okay like we have done in the previous scenario we need to understand so how to write the trigger by using which object operation and event so object can be determined by trigger has to be written on object on which user will do his action in this scenario while user is creating an account if annual value annual revenue provided by user is less than thousand so basically user is inserting an account and then we need to provide this letter if it is not matching this condition okay so trigger has to be written on account object here so object would be account now the next one is object is account now next one is operation so operation can be determined by the action that user has performed so in this scenario the action is when user creating an account basically he is inserting an account and then this logic has to be checked so the operation would be creation or like the insert operation okay so far we are done with object and operation now the event so even can be determined by before or after even can be found by using our thumb rule so you remember our thumb rule so thumb rule says if we need to update or pre-populate any fields on the same record or to fire an error validating the record then go with before event so in our scenario we need to validate the record checking for annual revenue less than thousand so this particular scenario is matching with before insert as this we need to fire an error validating that record we need to go ahead with this before event so the event would be before so finally the conclusion is for this scenario we need to write a trigger on account object insert operation and even would be before let's do that in salesforce so as per the scenario too we need to write the trigger on object account and operation is insert and event is before so this is pretty much same like the previous scenario right so it's the same object operation even so which means we need to write our logic in the same trigger and in the same block also okay because for one object the recommended thing is salesforce always recommend us to write one trigger only so account is only having a trigger so we need to write the same so we need to write our code in the same trigger okay now we will open the developer console and write our logic so let me open the developer console so in this case account trigger so whenever account is getting inserted it is coming into this trigger so as we have written before insert it will come into the bits before insert and these are the conditions i told you as if it is before it will be true and this if it is record is inserting this will be true so it will go into this condition now if you insert one record the sticker dot new will be having a list of records that are getting inserted and then it is checking the condition now the thing is we need to check in this for loop only we need to check one more condition saying that if this account record dot annual revenue is less than thousand we need to provide error simple so we will write a condition so this particular scenario which we have written here is part of scenario one okay now we are writing first scenario two okay scenario two which is throw error if annual revenue is less than 1000 okay so the condition would be if a c c r e c dot annual revenue less than thousand then we need to show an error so throwing an error is something which it can be done from triggers so we have a method called add error so that admit error method we can use it something like this so we need to mention the record name and we need to mention add error method and mention that and you can mention the error name here annual revenue less cannot be less than thousand and then save it so this way whenever you insert an account it will come here in that it will loop through that list as this is having only one record it will go inside it will check the revenue if it is less than thousand it will show an error if it is greater than thousand then it will come come down and then it will populate the billing address and shipping address accordingly let us see how it is working now so we'll go back to salesforce again the ui and then we'll create a new account so this is all about in insert operations only so create test account and i will scroll down i will give billing address and in the annual revenue i will provide value something around 155 okay which is less than thousand so the expectation is as we have given less than thousand it should throw an error and it should not copy the billing to shipping address because anyhow that should not work right so if i click on save it should throw me and saying that annual revenue cannot be less than thousand simple if i give thousand then it will process so which means our condition this condition will be bypassed and it will go down and then our logic of scenario one will be executed accordingly so we'll go back here and then as i have given so less than thousand it will error so if it is equal to 1000 or greater than that it will uh it will go forward so click on save now if i open the details see the values are copied over from building to shipping address so this is how you can pre-populate the fields from before insert and you can also you can file error based on conditions scenario number three i have another requirement when user created an account write the logic to create contact with same name and associate account and contact how to achieve this so what cuba is asking is so this is accounts tab right so whenever user creates an account let's say test account and then he create he just saves it okay he just saves it and account will be automatically created of course so as we are creating an account it will be created however as per the requirement which asked by cuba a contact also has to be created under this account with the same name as the account name that we have given so we need to write a logic to create a contact whenever account is created by user now we need to write trigger for this requirement so now we need to understand trigger hashtag which object and with what operation and which event we can determine that by using this text here so which object so far object trigger has to be written on object on which user will do his action in this scenario when user created an account so basically user is creating an account and we need to write this logic to create a contact so user is creating an account so the object would be account now what operation operation here is the action that user has performed so here the user is actually even user created an account so basically he is creating an account which means insert operation so the operation would be insert now the event before or after even can be found by using our thumb rule so what is our thumb rule number rule says if we need to update or pre-populate any field on the same record or to fire an error validating the record then go with before event but in our scenario we are neither doing pre-populating or we are not validating that record hence in any other condition we need to jump to after event as we are creating a new contact for that account so basically we need to go for after so the event would be after let's see how we can code that in trigger now we need to write our trigger so we need to write our trigger on so basically after the conclusion for scenario three we understood that object should be account and operation should be insert and even must be after okay however we already written a trigger on account but we have written trigger on before insert event so let me open that trigger so let me open this trigger and if you see we have written the trigger where we have button two scenarios one to pre-populate uh billing that billing address to shipping address and we also written another logic to throw an error whenever revenue is less than thousand okay now this is on before insert event but as per our scenario we need to write logic for after insert so how do you write it so basically whenever you write trigger on an object one object should contain only one trigger so you need to use the same trigger for writing after insert also so as we already have used before insert here to add our after insert you just need to use comma and then add your after insert okay so this is how you can add multiple events and then you can write your own trigger so this is the syntax this is the way of writing multiple events by using commas so as total we have how many events seven events if you remember we have before insert after insert before update after update before delete after delete and after undelete so you can write all the c1 events by using comma separated thing here so we currently put scenario 3 we are using after insert okay now this is when this if condition will come in handy sorry so we have trigger dot is before and trigger dot is insert so on before insert it will go into this if block and then it will execute our code but in after insert we need to write a separate code to create a contact so like we have done for before insert this if condition we will do it for after also so let me show that to you so what i will do here is before insert logic logic to be written return and they belong block okay now we have written our before block we need to write our after block also and then after insert logic to be written in this below block okay so if we need to write trigger dot is after and trigger dot is insert so what happens is whenever a record is inserted just before it is getting inserted it will call this below block and it will do this logic and once that record is inserted it will come to this block this is how this is how trigger works now that we have understood this ziploc will be called after record is inserted we need to write our code so whether it you are inserting one record or 10 records definitely you need to put that together. we have the trigger dot new right which is a list of so i have added here context variable dot new list of records that are getting inserted so let's say insert an account with contact name test it should create a contact with name test so we will write account acc rack and then trigger dot new so what we should do so for each of the account we need to create each contact let's say we insert one account we should create one contact so first we'll create a list of contacts okay con list to insert a new list okay we have created this list so this kind of coding is called bulkification of trigger because whenever it inserts a one account or it since it gets 10 accounts get incented from data and such it should work in the same way that's the reason we are putting distributor dot new in a for loop and then we are working on the logic so one for each of the account we need to create contactless so we'll just create contact instance new contact con dot so contact will be having set of fields we need to assign the last name contact should be having a last name field first name field we also have a last name field equals so contact name should be equal to account record which is getting inserted because the each account that got inserted will be there in this acc rec and then we need to get that name and then we will send it to conduct last name and once contact is inserted we need to assign this contact or like associate this contact or make uh i mean we need to make the this account to be a parent of this contact so that's the reason every contact is having an account id field we just need to map that account id feed here accr so before the account is getting created account id will not be available so that's one of the reason we are actually putting this logic in after so once that account is inserted only then we will be having the id right so we have the id and then we are associating with the contact id contacts account id so we have crea created the contact instance but we need to add this contact instance to this list okay con list to insert dot add and then we need to add that contact instance so basically we are inserting one account so this trigger dot so once that account is inserted it will go into this if block because as record is already inserted by then so after insert will return true both of them will return true it will come to this logic where we are for looping on that list so at that point of time trigger dot new will be having only one account so account record will be looped so we are creating a contact instance and account name will be uh populated with contact populated to contact last name and account id is populated to contacts account id to parent it and then we are adding into a list once we add that list we need to insert this contact list so that is something which we will do at the bottom so if we need to check the size of course insert dot size so whenever you are inserting a list you definitely need to check the size before you are doing it just do insert and then con list to insert so this is how you can actually insert the list you think this is done of course this is done basically we have after insert block where we have looping all the accounts which are getting inserted and then we are creating instance of for each of the account and then putting into a list finally we are inserting the contacts so let's try this and then see whether it is working as expected or not so click on save and then we'll go back we'll create a new account okay so click on [Music] test scenario three okay this is the name of our account so this is scenario theoretics and click on save and then it should create a contact you see a contact has been created this is the account a new contact has been created let me open this contact so contact last name is my i should be matching with our account id so account so scenario three this is the last name of account name so this is how you need to do your logic in after insert so we have learned a new context variable here which is ease after okay so let's copy this one and paste it oh so this is this is for insert i did mistake before so it's insert and this is after returns true if trigger is called after the record is inserted after the record is inserted or updated okay so this we have done so far so we are so far done with four context values there yet more to come but uh yeah this is the list so this is our after insert block and this is our before insert block okay and we just need to mention this is scenario three scenario number four i have another requirement when user updates account record if user changes account name throw an error saying that account name once created cannot be modified how to achieve this so basically what cuba is saying is whenever user tries to update the account name so we have the account name right so if we add change this account name to so and so value it should not change it's like our name and passport so we cannot change it right it's not easy to change it right so in the same way i think in account users shouldn't be able to change their account once it is created so clicking on the save now it is getting updated however the requirement is if someone changes account name it should not get updated it should throw an error for this scenario we need to try trigger so which object which operation we achieved so we'll see that so the object can be determined by trigger has to be written on object on which user will do his action so in this scenario when user updates account record so basically user is updating account record which means the object would be account and operation or which operation the action that user has performed insert update or delete in this scenario he is actually when user updates account record so basically user is doing an update operation so trigger has to be written on update operation now so operation would be update finally event so whether it is before or after even can be found by using our thumb rule so whatever thumb rule says if we need to update or pre-populate any field or fields on the same record or to fire an error violating the record then go with before event in our scenario we are actually trying to throw an error when user changes the account name so as we want to fire an error this is coming under this condition hence we need to go ahead with before event so the conclusion is we need to write trigger on account object on before update event let's see how we'll code that in trigger so let's see the events again so as per the scenario 4 we need to write account object trigger on before update even we already have our account trigger return right for before insert and after insert events we also need to write out before update event in the same trigger so let's open that trigger now we need to write our before uh update logic here so we already have after insert logic that have written for creating a contact and before insert has been written for two scenarios one is for throwing an error second one is for pre-populating it now to write our before update logic first we need to add our event in this one so if you don't add that event here this will not get called on your event okay if you want to write logic on so and so even you need to mention that event here okay before update if you don't write it here on before update trigger will not be called if you write that event here then only and whenever you are doing an updated this trigger will be called as simple as that so we need to write a similar logic like this for uh before update okay so before update logic 2p return in this below block okay now we'll write if condition if trigger dot is before and we'll be seeing a new context variable here trigger dot is update okay so this is the block where united where you need to write your logic whenever a record is updated just before the update if you want to write your logic you need to write it here in our scenario we need to write our logic to throw an error if account name is changed now the problem here is how you will know the account is changed account name is changed so we have our trigger dot new right so we can use the trigger dot new but the trigger not new will have the record insert that got inserted and you can trigger dot new will also have the values whenever you update a record so whenever you a record is updated if you want to see the values of it you can see it in trigger.new however trigger.new will have the values of the latest value let's say you changed account name from srikanth to srikanth 1. so trigger.new will be having the uh record with the name values equal to shri kant one it will not show any clue that the previous value is shri khan and it will not also say that it has been changed in the first place so that's the reason you will never find the value or like the previous value in trigger.new okay so then what is the what is the solution here so like salesforce has provided many context variables salesforce has also provided another context variable that context variable is called trigger dot old as the name suggests new will be having the record which with the latest values trigger dot old will be having the list of records which are having the old values of the same record of the same record the previous values will be there in trigger.old the new values will be there new trigger dot new okay so let's see whether it is really uh looking the same okay we'll debug log it and then you will understand old values and the new context variable is system dot debug trigger dot hold okay this is our new context variable hey trigger.told welcome to the club and then click on save so now we'll see whenever you are updating a record with the name then we'll see the latest values has to be in trigger.new and let's say i change from srikant to srikanth1 the valid tree is reconvened to be there in the trigger dot new shrikhand should be there in trigger.old let's see that okay so let me click here let me open a account so click on test123 so i will just change the account name from test1232 test123 update it okay and then we'll just conceive so as soon as i click on save if i go to the developer console and then open the logs so this is having the here says i think this should be it and then click on debug only so the new values if you see the new value says the name is equal to if you see let me test one two three updated okay old values it's the same list if you see it's the same id same record however it will be having the old value test123 so by comparing this record and this record we can say that whether it is updated so this records name not equals to this records name then obviously we can understand that the name has been changed simple okay now we have this trigger new and we don't know however we need to multiply this code so if we need to multiply it like that so we need to compare the names okay so which is like you need to write for loop on this new list and for each of that new list you need to compare each of the old list and then you need to write your comparison logic like new list record dot name not equal to all list variable dot name it's like new list of i something like that okay then you need to uh throw an error saying that add error it's just an algorithm it's not the actual code the syntax would not be same but this is how you need to do it if you are using this list you need to use two for loops so this time and because of this thing only we have maps okay so salesforce has created maps for you where you need to create uh id key value pair key value pair kind of thing however so for this kind of scenario salesforce as expected this kind of scenarios would be quite common that's the reason salesforce has given another two context variables on new and old list so those context variables are trigger dot new map it's the same list except that is a map it's a list is converted into a map where key will be the id of that record uh and value would be the actual record so trigger dot old map okay so let me see how they are looking so basically uh new map will be having id and value of i mean record with new values okay same here id id is the key and record with old values that's how it looks like so let's click on save and then let's see how that looks like we'll also see how it is looking like in the debug log so let me open another account so test account maybe and then i will change it instead of test account i will make it to updated and then click on save and if i open the developer console again and then open the latest log click on debug only which will open statements if you see new values and it's a new list i mean it's that a new new where it says the new value which is test account updated and the next one is the map where it says this this is the key key will be the id of that record and this is the record so key and that record record will be having the same new value and this is the old trigger dot old list where it has the name as test account which is the previous value and this is the key value pair this is key values id value is the actual record so in that record the name is test account so by using this map you can actually do the comparison easily without multiple for loops else you need to do you two for loops and then do it so in this scenario let me show you how i will be using that map and then comparing these records okay first i will just run the loop on the new list okay i'll just run the same loop like i'm doing it here so account acc rec and then trigger dot new so whenever you need to compile so this is a very very very common scenario to compare let's say you need to if this particular value is changed you need to do so and so logic so that kind of scenarios will come very quite often so this is the way that you need to do the comparison so remember this scenario this will be very much handy i have done this kind of compassion like 50 to 100 times in my complete career so that's kind of usage this particular scenario is having so now we'll change the variable of this one first so instead of accrace so that it is easy for us to refer that's it now we need to compare it so we need to compare this new record so your record will be there in new trigger.net new value will be there so let's say enter srikant i change it to srikanth one she can't win will be there this is record new dot name okay we need to have the old record also old account record also which is if we want to grab that we will create new variable i see all so this is a a variable which has to hold the old record values so for that we will use trigger.old map so trigger.totalmap is basically a map so from map if you want to get the value or like the record of it you need to use get operator so by using that i get operator you can get that old record however get in get operator we need to provide the key value what is the key old map and new map will be having the same keys which are the record ids so we can use the record id of the new record value which is acc rec new dot id as old map and new map or old records and your cards are having the same record ids ids would be same only other field value something like name phone billing address billing city etc will be changed so that's the reason if you ask gold map with the record id of the new record it will fetch that old record value with the old values okay now acc record new acc rec new will be having the values which are new which is like shrikhand one will be stored there and acc rec old if you want to graph it the whole value which is recon will be stored in this account record okay so now we will do the comparison okay if acc rec new dot name not equals to acc rec old dot name so basically this is the comparison this is the new record or like a record with new values and this is the record instance which is having the old values so new values dot name and old record by old values dot name does it match basically name has been changed if this is this condition matches basically the name has been changed in that case we need to provide an error what is that error so accrec new dot add error this is the method i think we already have seen in the previous scenario so add error is the method we just can give something like this account name cannot be modified or changed once it's once it is created okay so let us save this and what is the error yeah so just take this page out done so let's save this one so whenever you want to compare so basically this kind of scenarios are very much common whenever you need to compare uh saying that if if that particular field has been changed do so and so logic this kind of scenarios are very much common so if you want to compare between phone you need to do the same accrc new dot 4 not equals to accreco dot phone same with any other field you can do multiple fields so comparisons has to be done like this get that old map and get asked the record id so that it will find the it will give you the record or which will be having all values and you can compare with old and new record values like this so let's test this out so i will quickly go back to the uh salesforce and then i'll open and one account and i will try to change this account name so test account updated now and then if i click on save it should provide me an error saying that you cannot modify it you see account name cannot be modified or changed once it is created and voila this is how you can add validations in before update by comparing old and previous values in this scenario you need to really understand how i have done this comparison this is very very very common scenario and let's comment this this out quickly and yeah and we have learned new context variables right which are old map old new map and we also have learned old so let's add that one also so context variable has to be so context variable 5 is trigger dot new map so returns the list of returns the list of records that are inserted or updated with latest values okay and it's the same thing we can do the same thing for old map except that it has to be having old old map that turns the list of records that are inserted are updated with old or prior values okay let's say i change from srikant to srikanthan shrikant one will be there in new maps she can't be there in old map simple so and that too and we need to mention in map format and map okay and we also have got new context variable which is old trill dot old it's the same thing new map and old map so which will be having the old or prior values yeah that's done reduce the list of records that are inserted or updated with older priorities done we forgot one context variable here which is update so is update so we have before is before is insert is after right the same way we should be having is update so this is the context variable we have used it here so is update and the context variable number is 8 returns true returns true if trigger is called when record is updated simple and then yeah so we are done with the context variables for all these four scenarios scenario number five i have another requirement on user updating account record if billing address is changed update all its sale contacts mail address field same as the accounts billing address how to achieve this so what cuba is asking here is so let me open any account that salesforce has already given so so let's see this edge communication so we have an account which is edge communication and it is having two contacts okay now if we go to details and user changes the billing address here then automatically we have in contact we have addresses in contacts for each of the contacts so this is the first contact and this is the second contact so in the first contact the address which is the test here this address has to be updated based on this address so let's say if i change this address to something then automatically that value has to be reflected both in contact one mailing address and contact two mailing address which are associated with this account for this scenario we need to write the trigger so which object which operation which event that can be determined here so object trigger has to be written on object on which user will do his action so in this scenario here on user updating account record so hence the object would be account and the operation now the action that user has performed in here user is actually updating account record so in that case the operation would be update and finally event before or after event can be found by our temple so what does our thumb rule says if we need to update or pre-populate any field on the same record or to find an error validating the record then go to before event in our scenario we need to update the record however we need to update its shield records not on the same record so user is updating account and then chilled records has to be updated as per the logic but in here this is completely different this is updating the same record or firing and validation error as this is not satisfying this particular condition here we need to go ahead with after event in any other condition jump to after events so the event would be after so we need to write sugar on account on after update event let's see how we can do this in salesforce so let me recap the requirement again so we have account which is associated with two contacts contact one and contact two so on account if billing address is changed that address has to be copied over to its two contacts contacts first mailing address and contacts to change mailing address so this has to happen when our account updates its billing address user updates billing address on this account so as we have already understood we need to write trigger for this scenario on account object on after update event so let's open our developer console and the trigger that we have written as we already know we are writing trigger on account so that's the reason we need to use the same trigger again because we need to write one trigger for one object that's the recommendation so we have already three events that we have added here we need to do the after update even right so if we want to add our after update event we just need to add this here after update so this is how you need to add your new event every time you are working on the same trigger okay so as you already know if you want to run your block once the record is updated like after the update you need to write your if condition again so after update logic to be written and this below block will just follow the same thing that we have done before so before update we have written like that after insert and before insert let's say we will write it again for after update also if trigger dot is after and trigger dot is update then we need to write our logic here so what is the logic if as account is getting updated then it will come to this logic we need to check if the billing address is changed if with the billing address is changed only then we need to go forward and then update our contacts so to check whether a particular field value has been changed or not we already done that thing right so we can just get that old record and we need to run the for loop we need to check the old record and then we need to get that name and then the previous values name and then we just compiled it in the same way we need to write for loop here also so first we need to loop loop here on account acc record new and we need to run on trigger dot new now we need to understand let's say we have inserted or like we updated one account district dot new will be having one account let's say we have updated 10 accounts uh from data loader or workbench assets district dot new will be having 10 records then okay now we need to compare it with the i mean we need to get the old values record also now so how we will get it so we'll create an instance here account acc rec hold and you know right we just you you need to use the old map here so which is the same as this we need to get trigger dot old map so what does that old map returns the list of records that are inserted are updated with the old prior values in map format so this is old map omap will get the complete uh records list which will be having the prior values okay so during this map we need to get our record by using the get of get function and we need to check we need to get that record by using its id so get rekt new dot id yeah so now that we have so from this map we are getting our record id which will be having our old uh old values in this account now we just need to compare these values and this values building city billing state billing address and such but at this point of time i really don't want to compare each and every field so in our scenario let's go back here and if we see we have what is the first billing field it's a billing state so we'll just write it only on building street logic so if acc rec new dot billing street not equals to acc rec old dodd yeah billing street so if both are not equal that means that billing address has been changed we are particularly only checking on billing state we really don't want to check every other field on that billing address if you want you can just put our operator and then acc dot billing city not equal to acc hold down billing city and so on you can just do that but in this scenario i wanted to only check building street change here so now that if we understood if both of them are different that means this particular record is basically got changed i mean this will be records this particular account billing address has been changed okay we need to track that account id here so we need to put that account in a set here i will tell you why we are using set here so id and then acc ids which got billing address changed okay new set so this is a baluchification of code that's the reason we are using this kind of logic else it is like we will now we know what our account has been done we just really don't need to have set sender but this is publicification accord if 10 records got updated and out of which only three records updated its billing address this set should capture those account ids for which billing address has been changed so dot and by using ad operator you can add your account ids into this set so acc rec new dot id so what we have done so far so we have we have compared each of each we compared the old value and new value of that record if the billing state has been changed then we are adding that account id into a set because we need to query the contacts also right and only then we can update the contact so at this point of time we got let's say if we insert one account and if that billing address has been changed the set will be having one record let's say you have updated 10 account records from workbench or from data loader this will loop through this will loop for 10 times and if the skip condition will check the billing address has been changed to each of the account let's say out of those 10 only three accounts of are being updated with that billing address then this particular list will be having those three account ids that set which is this set this set this set will have account ids which got billing address changed okay as this is publicification this is how always you need to work on okay and then as we got the set we need this is the time to query the contacts so don't don't actually query contacts separately you can just do it on account so i will tell you why we are doing like this but yeah accounts with contacts you can query accounts and contacts in a single query okay so how to do that select id comma maybe name and if you want to uh get its child or records also let's say for one account we have two contacts so this is how they will get it so select id select id name maybe and we also need to from contact so we in in this inner query whenever you are using you need to have this contacts instead of contact it should be contacts so in this scenario whenever you are querying contacts within a single query of account you just need to use contacts not contact okay so in a single query just need to use select id name from contact but if you are using with account like in this inner query you definitely need to use contacts that's the name salesforce has given okay where we need we should be getting all the accounts along with its contacts what are the accounts we need to get it we need to get only the accounts in its contacts where billing address has been changed the set is having the list of account ids for which billing address change right so we'll just query based on this so where id in or this particular set now this query will be having all the accounts this query will be having all the accounts for which uh contacts address has to be changed however we need to get the billing city billing address completely from here so building city because we need to put it in contacts right so building street building state building country let's have only these four okay so what we would do is we need to run loop on this and then we will update the contacts okay so we need to have a separate list where we need to add our contacts so list of contacts contacts list to update and this is an empty list contact okay now we need to run for loop on these accounts and then for each of the contact will change the address so for loop on this account acc and then we need to get this one so we need to get all the contacts list right so what we will do is contacts contact we will put all those contacts in a list first c o ns of of the looped account and we need we can actually grab that accounts contacts by using this kind of like this kind of value so acc dot name will bring acc dot a account name acc dot billing city will create as as is a billing city in the same way the contacts of its account can be grabbed by using this acc dot contacts whatever name you have used it here you can get it like this so by using this it will list it will return the list of contacts associated with this current account and we are putting into a list and in this list we need to loop it again and then finally we need to update uh the billing city into this mailing city so what we need to do is we need to run loop on that again contact con we are running loop on this contacts okay and what we need to do we need to update con dot mailing street is equal to acc dot billing street con dot mailing city equal to account dot billing city same with the other fields mailing state billing state what else is left billing citizen state and country con dot mailing country equal to acc dot billing country so we have our four free content we just updated these contact values and then we just need to add this contact into our list so we'll just add this into our list add and then cyn okay so it will loop through all the contacts of that account and it will update the billing address into the mailing address and we are adding each of that contact into this let's say we have only one account updated that one account will be there and it will fetch its contacts so in this particular line we are getting that account contacts let's say we have two contacts two contacts will be there in the list so we are looping through those contacts so first contact it will be having the mailing address value populated with the billing address value here and it will be adding into this empty list so this list will be held looking one contact now again the second contact will be loop here and then it will update uh with the billing address from account and into into mailing address here and then it will be added into this list finally this list will be having two contacts with the updated address okay finally once we are out of these loops we just need to check the size and then we will update it so cond list start science whenever you are doing it always remember whenever you are updating or doing a query never do that in for loops okay so we will just update it update okay and click on save so let's recap what we have done so here we are whenever an account or whenever account or account is getting updated we are actually comparing the billing addresses if the billing state has been changed here we are only checking for one field if billing street has been changed we are adding that particular account into a set so based on that set we are actually querying the list of accounts for which billing address has been changed where we are querying we are also querying the contacts also in that single query itself so we are looping all through the accounts for which uh billing address has been changed and we are grabbing the accounts of that each account and then looping them and for each account we are updating the billing address of that account into the respective child contacts and then we are putting into a list and finally we are updating that list so we are done with our programming part now it is time for us to test so we'll go back again here and then what i would do is we already have open this one right so currently for edge communications there are two contacts where we have the meaning addresses three one two constitution palace and whatever this one three one three constitution palace so i would change entirely okay what i would do is i i change the billing address this should reflect in child contacts same as above same as above maybe this one and country same as above and then i will click on save now and we'll see whether these values are updating into these contacts accordingly okay so let's click on save okay let's check this one out refresh this page and then we should be seeing the latest change here you see this contact i change the building address they should reflect initial contact same and suppose same as above so let's open this one and refresh this one too and yeah we got the mailing address changed okay this is how you can update the chill records in the after update event scenario number six i have another requirement an active account should not be deleted how to achieve this so basically what cuba is asking here is so every account will be having something called active field so it can be either active or inactive by you can choose that you see active it's a drop down active s or no let's say if we have an account which is having active status if we are trying to delete this account it should not let us allow to delete it so that's what the requirement is but this scenario will write the trigger so however which object which operation achievement so that can be determined again by here trigger has to be written on object on which user will do his action so an account should not be deleted so basically user is deleting an account which means the object is account now operation the action that user has performed insert update or delete in this case users actually should not be deleted an active account should not be deleted so the operation is delete and finally the event before or after event can be found by our thumb rule this thumb rule will help us to determine whether to select before event or after event primarily on insert and update events to select on insert and update events so however but most of the cases even in delete operation also we can actually use this thumb rule this number will also help for the scenario which q by has just asked so if we need to update or pre-populate any field on the same record or to file an error validating that record then go with before event so in our scenario we need to file an error if it is a active account right so we need to fire an error in this case we need to select before event as party thumb rule hence the conclusion is we need to write trigger on account on before delete event let's see how we can do this in salesforce so as we have understood any account that is having active status yes should not be deleted should not get deleted it should file some error okay so to do that we definitely need to write our trigger so this for all these errors that we have tried earlier can also be done by flows however i have shown you how to do that in triggers because so those are very easy scenarios which will help you to understand how triggers work so this is the scenario definitely need to choose triggers let us see how we can do that in trigger so before that we need to understand what is the event so here it should be on account and be 48 so as we need to write our trigger again on account we need to open our trigger that we have written earlier it's the same trigger except we need to add one more event so you know right so whenever you need to add one more event you just need to append that event here so so far we have written our trigger on four events now the new key down board is before delete okay now as you have already seen every time we are writing an event and if you want to write some logic for that particular event you definitely need to write your if block again okay so what you need to do is before delete logic 2b return and this below block okay and now we need to write our if condition here trigger dot before sorry q dot is before and trigger dot is delete so in this in this scenario we got new context variable which is easily so this is a context variable which will let us know that whether this trigger is getting called or delete operation so whenever his trigger is getting called uh and before and it is getting deleted just before the deletion this logic will run water logic we are writing it here okay so we are telling salesforce to run this trigger on before delete by putting this event so if you put this event whenever a deletion happens just before the delete this trigger will be called but to run our logic you need to write trigger dot is before and trigger dot delete same with the other events too okay now trigger dot is before and figure dot is delete now we need to write our logic here so what is the logic we need to look through the records that are getting deleted so in delete so now the scenario is in delete when whenever you look through the delete operations basically you're not giving a new value basically clicking on delete for that reason trigger dot new will not be available in before delete operation so let me point that out so trigger dot new is not available and before sorry in delete operations whether it is before delete or next coming even which is after delete okay then how you will understand what is the record that is about to get delete and how you will know the status of active status of it only then you can file error right so if you don't know the status of or if you don't have the required data into this block how you would file an error so for that you have trigger.hold so trigger.old is available okay so figured out when i say trigger new it's both new and new map which are this one and this one is available so trigger dot old and its map and map old map are available available in delete operations okay it is on both both before delete and after delete also now that we have understood we need to write our for loop on trigger dot or so let us see that for account acc new sorry acc old it should be trigger dot hold so we need to look through let's say record is getting deleted let's say you are deleting records in bunch in mass delete then all it can record let's say you delete 10 records at once by using data loader or workbench or you are clicking on all these checkboxes and clicking on delete button at once then this trigger dot will be having all those 10 records if you are just deleting one record this tickle.old will have that one record so as we have got that as we got that listing to this for loop we just need to check the status of it here if acc old dot active active is actually a field that has given by salesforce equals to yes then what should happen so you're trying to delete then it will come here if that's the account status is equal to active status is equal to yes we need to provide an error so you remember right how to uh how to find an error we have method called add error you need to mention the record name and give that error okay add error you cannot delete an active account good now we have done our logic see very easy so writing trigger is pretty pretty easy except that you need to understand what are the context variables that is it so let us try this out let's test this out so we'll go back here and then this is an active account right of course this is active account let's delete this we have delete button here and i click on delete and it says you cannot delete an active you can see as easy as that let's try another account so this is test123 which doesn't have any contacts let's see yeah let's make this active status yes and then click on save and if we try to delete this one again and it should join us saying that you cannot delete an active account let's say we'll make this active to no and then we'll try to delete this account okay and then click on delete now this is active now so expectation is this record get deleted because the active status of the code is no okay see the record got deleted and hola scenario number seven i have another requirement whenever user deletes an account send a confirmation email to the user how to achieve it this is very much self-explanatory so for that also we need to write our trigger so on which object which operation which even can be determined here trigger has to be written on object on which user will do his action in this scenario user deletes account so basically the object is account operation now the action that user has performed in here user deletes account so the operation is obviously delete and before or after even can be found by our thumb rule as per the thumb rule if we need to update or pre-populate any field on the same record or to find an error validating the record then then go with before event else we need to use after event in our scenario neither of these conditions matches so we need to go for after even hence the conclusion is we need to use account object for trigger on after delete event let's do that logic in salesforce now so basically whenever this account is deleted we need to receive an email so let's i delete this record then i should be receiving a confirmation email okay to do that we definitely need to go to trigger so as per the scenario we need to write a trigger on account object and after delete even already we have a trigger on account objects so we need to open the same trigger and then we need to add our logic so go to developer console and we already have five events now we need to add over six even so after delete so by adding this event here we are basically telling to salesforce that whenever deletion happens after the delete operation please come to this trigger so by having this on account deletion after the deletion operation salesforce will come into c coming to this trigger to see if there is any logic written on it so we need to write our logic in our after delete block so we need to write our after delete block here so like we have done for before delete another after update etc so we need to write our if block here so it should be after delete logic to be written in this pillow block okay now we need to write our if condition trigger dot is after and trigger dot is delete now we need to write our logic here so what is the logic sending of email to sending email to a user who delete who has deleted the record who deletes the record okay now in here we also need to understand as we have discussed earlier trigger dot new and two dot only will not be available why they are not available whenever you open a record and provides new values to it and then save it that new value state or the record instance will be stored in this trigger dot new the previous values instance will be stored in trigger.old in the form of list you have done 10 records update or 10 records insert those values should be stored accordingly in this lists accordingly how whenever you are doing delete operation you are there is no chance that you will be providing new values on that right so hence trigger.new is not available because you are not providing any new values there trigger not only something as the old values are already there you're just deleting that record hence sticker.old is available in delete okay having been said that we need to send emails right to send emails we need to process the record once we process the record we will get the account name etc and then we will use that account name to send emails okay so we need to run loop on the records so account acc old trigger dot told okay now in here we need to write our a logic so remember this whenever you want to send email this is a standard course input you can find it in google very easily okay so i just remember the code i think so at least so we'll try to see if i if we can write that directly so new messaging messaging dot single email message so we have created this single email message instance so here we need to provide the two address to address to address basically takes email addresses in the form of list okay so to whom we need to send this email so the person who has deleted it basically the current user who is actually part of uh who is actually deleting it we will take that email id so we need to create the email list first so string email is because whenever you send emails there is a chance that two can be par two can be given multiple emails right that is the reason email to two addresses basically it will take strings but we want to send it only to the person even though we want to send it for single person or multiple persons we just need to add that into a list of string first okay email addresses new so this is an empty list at this point of time now we need to add the current user email address into this email address list so current user email address can be found by using standard method which is called user info dot get user email i think it should be there yeah you see example get user email so you can also get username user id etc by using this standard but this is the standard method okay username is a class and this is a method so we need to add this email address here so now we have created the email instance and we have given two addresses the current user email id so is it enough we also need to provide the subject and body also so we have something called set subject so in this subject we will try to provide some text saying that account has been success fully deleted and i always get confused with successful reward yeah and then plus now here you need to give the account name how you will get it this account acc old dot name simple so we have the subject now we also can write body you also have some other method like you can set bcc at the cc address you can also give attachments etc okay so here i will just make it as set set plane template body where is plain template plain text for yeah and in here you can just provide the text hello nobody return here please refer subject okay and then we are done with creating the email instance however if there are 10 records deleted i mean if there are more than one record is deleted then we need to send more than one email right whenever you want to send emails in bulk whenever you want to do dml operations in bulk whenever you want to do a query do a query do not do that in for loop so hence we need to add this email instance to a list first so we need to create the list here so list so what kind of list so this is a single email message for which we can send image so we need to create this list email objects ding ding and then this and then here so we have email message object it's a list now so we need to add all our email messages to this list okay so we by this for by the time this loop ends we have the email message objects where it will have the email message instances let's say you have 10 records deleted this email objects will have 10 email messages ready to send email okay so to send email we have a method again so which is messaging dot send email and hit in this it will take list so we'll just take this list and then put it here so do you think it is done yes this is done so whenever a record is deleted after the record is deleted it will come here and it will create i mean we have created an empty list of email messages and in for loop if we have one record this will create a single email message and it will have two address with the current user email id subject with so and so subject with account name and plain text it's a simple text and then finally we are adding that email instance to your list so if it is one record this list will be having one one email instance and if you send email one email will be sent there okay if you have 10 requests and emails will be sent simple so let's save this what is this error we will quickly see it yeah the it's not to address it set to address set to address set to address set to address okay this is set to address not to address okay and then we should be good okay now we have our trigger let's see how we can test this so let's go back to this one so we have this account so we will try to delete this account here so we just need to confirm that this is active is not equal to yes so yeah errors or before delete uh scenario will stop us deleting it i'm deleting this record so i should be receiving an email so let's delete this click on delete our record is deleted so if you see this email i got the email saying that account has been successfully deleted and the test account name that's the name i should have kept a column here but yeah so you can say that this is except whenever you get email from salesforce you will get this kind of spam you just need to make it mark it as look safe hi nobody no body written here so please refer subject so this is how you can send emails from trigger scenario number eight i have another requirement send an email to the user when user restores an account from recycle bin how to achieve this so for this scenario we need to restore the record from recycle bin so recycle bin can be found here in app launcher we already deleted account right the latest record that we have deleted is this if i'm not wrong so i can just click on it and then you can make it resource by clicking on this account will be restored back to the account table okay so once restore is done restoration is done current logged in user should be receiving an email saying that so and so account has been restored that is for our reference okay for this scenario we need to write the trigger so which object which operation which even so the object can be determined by trigger has to be written on object on which user will do his action so send an email to the user when user restores an account from recycle bin so he restores an account user restoring an account so basically the object would be account here now the operation the action that user has performed insert update or delete neither of these actions he is performing he is restoring it so there is one more operation called undelete operation hence the operation is undelete so trigger has supports this undelete operation and now the which which even so in in undelete operation salesforce has only one option it is after undelete there is no before and delete so the conclusion is we need to write a trigger on account object after undelete even remember people will confuse very quickly in salesforce we have only after undelete there is no before and delete remember that we only have after and delete for this scenario we need to write a trigger so trade has to be returned for this scenario is account trigger on after undelete event so we again need to go to our trigger which we have written earlier and then if we scroll up we only have six events at return and we need to add our seventh event so these are the seven events that salesforce allows to write on trigger okay usually not every time you will be writing all these seven triggers based on the requirement you would do it but it is absolutely uh common sometimes where you need to write all the seven events okay so on after undelete even that you have added here in the trigger so whenever undeletion happens whenever user delete undeletes or like restores a particular account then this trigger will be called so you need to write your logic and your logic will be called so your logic has to be kept in again another if block where it will say trigger a dot so after after and delete logic to be written in this below block okay now the thing is we need to write our if condition here which is trigger dot is after and trigger dot is undelete okay so this trigger dot and delete is a new context variable okay now we'll add here so i think i haven't added this sugar dot undelete until not easily contextualized let me add that right away so these are context variables 9 and 10. so these are standard variable standard variables that have been given by salesforce for us to easily write our code so ease delete is undelete so returns true if the trigger is called when the record is deleted and this is undefeated simple so we have all our context variables covered there are a couple of other context variables but these are the primary ones okay now after undelete now we need to send email to the current login user if you see it's very much same like this previous scenario i think we can very much use the same logic okay so i think yeah let me add that sending email to user who deletes who restores the record however we will not have we will have trigger dot new in undelete operation why because it is getting as a new record into salesforce however salesforce id would be same whenever you restore a record salesforce id would be same but it will be added as a kind of new record because that record was not there now it is coming so that's the reason till.new is available and available in undelete okay understand undelete is very much same like inserting records and delete an insert operation will have same kind of context variables okay so understand and delete as very much like new okay so trigger dot old or old map is not available not available in undelete okay now that we have understood trigger dot new is available until dot old is not available older old map basically a newer new map now what we need to do is we need to write uh i mean basically you need to create a list same like this we need to create the list of simple message and we need to create we need to create the email messages and then set to address set subject set pain body so we'll just copy paste this okay however there is small change that you need to do so instead of trickle.old it should be trigger.new and we'll change the variable name also so account new and account new so if we see account has been successfully restored i think this should do so in after and delete we are creating a list of email messages and for each of the record that got restored it will run loop let's say three or four records can be restored at once or it can be more then four email instances will be created with the set to address as the current user email address and subject is you account has been successfully restored plain text body is just a text body and then finally you are sending email send email is the method which is actually sending the email okay here we are actually in the email message it's like composing of email this is where you're actually sending email message i hope this is clear so let's save this and test this out and trigger has been saved so let's restore this and this out so we'll go back to recycle bin so this is the account which i want to restore and then if i restore this it's and if i go to email and then check it i should be seeing an email and if you see i got an email saying that account has been successfully restored and it is test account okay hello nobody has written no body reader here please refer subject so this is how you can do some logic in after undelete operation also whenever the record is being restored from recyclable you can do your logics simple so far the summary is we have gone through all these scenarios right so for each of the scenario we were able to find the right trigger event so example for the first scenario while user creating an account if user provides billing address but not shipping address we need to write a logic to populate shipping address with billing error site for that we understood that we need to write it before insert where while inserting itself we will write our logic before insert itself we will write our logic same with the other scenarios correct so in reality or like in real time scenarios you might be getting a requirement something as easy as this where you might be using only one event for your scenario you might also get some complex scenarios where you might need to use combination of events something like before insert after insert or like before insert before update or after insert after update after delete or before delete after undelete so it can be of any combinations you name it it's based on the requirement you might need to choose the trigger events let me explain that with an example so in this case we have find out some of this sample combos so before insert and before update can be one combo for a given requirement after insert after update after until it can be another combo for another requirement and before delete after delete can be a combo for another requirement let us see that so first requirement is throw error if phone number is empty so whenever a account or like a contact is getting inserted if the phone number is empty if you want to throw some error you can do that in before insert and before update you know you know right so we have the thumb rule whenever you want to throw an error or pre-populate field on the same record then you need to use before events so in our case while creating itself they can give phone number empty or they might be updating the existing phone number to be empty so in both the cases we need to throw error that's the reason you need to sell before insert and before update so sample combination two sending an email if new or existing accounts active status is set to active let's say we have active field on account while creating the record itself they might set it to active they can also update an existing account to set it to active so in both the cases we need to send email so that's the reason we have after the insert if they have the value active status value true then you need to send email same with after update so if someone changes the active status from not active to active then also you can change and email in after update however there is one more event here so after under let's say an existing account which is deleted and that is in active status you are trying to restore it and then also it is an active status right it's like a new record there that's the reason after under it also you can write your send email logic now comes sample combo 3 here we have two events before deleted after let's see the requirement don't let active account to be deleted you already know it if you want to throw an error when an account is getting deleted you can write it in before delete before in because before the delete itself you can check whether the account status is active or not and then throw an error and if inactive account is deleted delete its shield custom object records also let's select account high is being deleted and it is an inactive account account will be automatically deleted because we will not stop it so as it is an inactive account however we also need to delete all itself custom object records so that we need to do it in after delete so in this way based on the scenarios you need to select your combination of events it can be a single event it can be multiple events it can be combination of any events or all the events also it's based on the requirement always try to break your requirement into pieces and then try to find your events it's very easy now we will see best practices while writing epic stickers there are multiple best practices that you need to follow we'll see one by one first best practice is one trigger per one object so let's say in our previous scenario we have written all our seven or eight scenarios in one trigger itself so we should be doing that in one trigger all our logic has to be kept enough one trigger salesforce will still allow you to put it in multiple triggers but do not do that the reason is let's say we have two triggers let's say we have two triggers on account i can't trigger one and account trigger two so in first trigger we have return on bins before insert event saying that amount has to be pre-populated with 100 and in the second trigger let's say we have written a logic if amount equals to null throw an error okay so in salesforce order of execution of triggers is not guaranteed if multiple triggers are written on same object in this case let's say we have written two triggers like this it can sales person execute the first trigger first and then second trigger letter or it can execute the second trigger first and then execute the first trigger letter so let's see what would be the result if we follow this uh order and we will see what would happen if if second trigger will be executed first and first to get executed later so in this scenario in this order so a amount is pre-populated with hundreds amount value is set to 100 as per first trigger and as per the order if we come to this trigger if amount equals to null as amount is already 100 amount cannot be equals to null so hence it will come out of that if condition finally that record will get inserted with amount equal to 100 hence there is no error okay however if salesforce follows this order executing trigger too fast it will check if amount equals to null by that time if no one provides amount value amount will be empty and it will throw error and it will not come to the second trigger in the first place i mean it will not come to the next trigger in the first place and then it will show an error directly and then a result will be error so see based on the order of execution the results changes that's the reason salesforce always recommends even though salesforce allows you to write multiple triggers salesforce always recommends you to write one trigger per one object so that you can decide your order i hope you understood what is the problem of using multiple triggers under the same object next best practice is bulkify your trigger code should work if records are inserted updated deleted or undeleted in bulk what does that mean exactly so whenever you write your trigger do not assume that always your user will provide you the values from user interface we have your new button right where you will click new button and then provide values and then click on save it is not necessarily same every time so that we might be creating a csv file and then uploading set of records like tens hundreds or thousands or lacks of records from the data loader or workbench so your trig error should be able to handle whether user provides data from user interface or they will be providing data from csv file via data loader so that kind of data providing from data loader or workbench because they are providing the data in bulk rates that's the reason if you need to write your trigger definitely write your logic in such a way that it will handle multiple records are loaded at once let us see the publication with an example so whatever we have written here is all about the multiplication itself so we have written the account to your right so it's all bulky fed so if you see let's say after the insert let's say we have 10 records inserted it will go inside and for all the current records the account loop will run and it will create contact instances and the contact instances are kept in a list and finally out of the for loop we have inserted the list so let's say we have 10 accounts created so equivalent content contacts will be created by using this insert operation let me show you how the code will be if there is no multiplication so i'll create a new trigger on contact and then i will show you contact trigger and then on contact and then click on submit now you already know right whenever you want to write some code you can just put that in trigger dot is insert and is insert sorry before let's say we have the requirement to pre-populate the contact last name with abc so we can do that in this way okay so if it is not multiplied code so this is a list right so trigger not usually so we will take the first record of that trigger so this is a list and basically array so i wrap the first record array of the first record dot last name equals so whatever user has provided plus abc okay now if we do this this code will obviously run and then it will obviously work however by doing this let's say if user creates one record from user interface it will come inside and it will check the last name and then last name plus abc will be assigned to last name so let's say i have given srikanth in the uh user interface in the under last name then it will insert that she can't abc this will work obviously but it will only work if you are inserting it from user interface and if you are inserting only one record however if you are inserting 10 records the first record will work rest of the 9 records will not have this value updated properly so if it has to be updated properly then you need to write your logic in a different way non vulnerification of code okay let's see how the multiplication code looks like well keep fight i will comment this down okay now how to write bulky file code here so it's the same we need to write this block trigger dot is insert and trigger dot is before this is something which we have already seen already has done so but i will just show it again contact cyn trigger dot new and inside con dot last name is equal to contact last name plus apc so now let's say if 10 records comes into the trigger so for each of the contact we are assigning the last name equal to current class name plus abc so if we provide shri khan it will be saved as you can't abc let's say you have inserted 10 records with 10 different names for all the 10 names will be abc will be appended at the last but if this if we do this in this way it will not work that way so this is how you need to bulk for your code so let me save this and done next best practice is avoid dml statements or social queries in for loops as it will hits govern limits so we have a governor limit of using 150 dml statements in a single transaction or 100 queries in a single transaction let's say we inserted 100 records or like maybe thousand records and then you will run for loop for trigger dot new right let's say it inserts thousand records you will run for loop on that trigger dot new list then what happens is if you do any dml operations or sql queries in that particular for loop obviously this loop will run 100 thousand times if you have your dmal operations then within the first 150 statements itself dml will hit the error and the sql is having just 100 queries then within the 100th loop itself this will hit an error so that's the reason whenever you need dml operation server circles queries to be written put that outside the loop you can use maps lists etc etc to have that sorted and then put everything every dml operation or soquel outside the for loop never ever use these statements inside for loop it's not only for triggers it is applicable for entire apex next one is do not write logics in trigger use trigger handler instead what what is this so we have written all our logic and trigger right then what is this trigger handler so let me explain that to you now so this is the trigger that we have written so we have written almost seven scenarios where we have written our logics inside these events right so even blocks so we have written another logic in another event which is after delete talk so under before delete block we have written another logic however salesforce requires us to put this logic in another class and call that class from distributor so let me show you how we'll do that so cut this logic whatever we have written for after and delete and we will put it in a separate trigger handler so new and click on class and then account trigger handler you can define any name but trigger handler is a standard okay so click on ok any class can be called as trigger handler if that class methods are being called by trigger symbol so we will create a simple method saying that public static void and send email on undelete and then put your logic here okay so now this logic has to be run and this has to be called from this trigger so what is the class now we can this is a static method right whenever i messed whenever it's a static method you can call it by class name so class name dot dot method name and this one however this particular method needs to get out new right here it needs to get new to run the logic however trigger.new is a context variable which is only applicable within apex trigger so we will send trigger.new here okay but we will receive it as list of accounts which is your staff accounts and then install trigger dot you make it as new or like account list new to understand that set trigger dot new that has been sent from trigger so here just replace trigger dot new with account list simple so i just saved this one so we have moved the undelete logic into another class in a method where we are receiving the trigger dot new into this parameter and then it is looping through all the parameters and we have this and the main logic here so now we will go and click on fx trigger and we'll just save this one so if you see we have moved our after and delete logic completely into apex trigger handler we can do the same for others also so let me do that for another one copy cut go here and this is also send email if i'm not wrong so public static void and send email on after delete and then paste our logic thing will go back to trigger and then we can call the call that method particular method so what is that method name which we have written send email and after delete okay so we need to send what what this method is expecting we are using trigger.old here no so that's the reason we need to send trigger.old here okay so to receive this trigger.old we need to take this parameter we need to input the parameter here so list of account and then acc list hold and then copy and paste it here and then done see so this is how you need to put all your logics you just need to cut all your logics and then put it in another method and finally this trigger should be only having if block and it should contain the calling of trigger handlers so this is what is called any class that is being called or any class methods that are being called from triggers or nothing but trigger handler so we need to use trigger handler to put all our logics here and then call the respective methods from triggers like this okay so if someone asks what is trigger handler say that trigger handler is a class where it has the methods and logics which will be called from trigger done next one is avoid hard coding of ids in apex triggers hard coding in the sense giving some values which cannot be altered unless and until you update the program so let me show you one example so let's take this scenario yeah so in after insert logic we have written a scenario where for every account created we want to create a contact to be also be created so if we want all the contacts to be associated with a specific account id you can just queue like this right so we can just hard put the value saying that so account records will be starting zero zero one so if we give something like let's copy the url from somewhere and then you can just give this account ready like this let's say these ideas will be changed across the environments let's say you provide some hard coded id in uh different environment later when it's when you move it to qa or when it you move it to uat or production that same record will not be there in uit you're in production that's the reason this will fail you're trying to assign the account id with some hard coded id which is which will not be there in the uh further environments that's the reason never ever hardcode your values in epic stickers not only in apex triggers never hardcore in apex classes at all if you want to use some hardcoded values in your trigger you can use custom labels custom settings and custom metadata and then referring to your code so that in production it is easy for you to change next one is prevent recursive triggers so in triggers there is a chance that our trigger will be called again and again and again in a loop it's like an infinite times of calling so we need to prevent that to happen so this is also in three questions we need to know how to prevent triggers to be called recursively let's see with an example so let's say we have a user who is actually creating an account from user interface once user clicks on save salesforce calls triggers after user clicking on save so now let's say we have after insert event logic on account trigger so here in after insert we are inserting another account when user is creating this account we are also trying to create a duplicate account in this account object so we are clearing the second account as per the logic in after insert event so what happens here is so user clicks on save an account will be created and then it will go to opt-in set and another account will be created as soon as another account created basically we are doing a dml operation account which means it will call trigger again why because we are actually doing an insert operation here so this insert operation will again call the trigger and in the trigger we have after insert logic and again it with this logic will run so this logic it will be creating another account which will be third account now and then it will again do an insert operation and then it will create call the trigger again because a new account has been created again this blue blue loop under the trigger depth is reached uh as this is an infinite loop trigger will throw an exception saying that trigger depth has reached as per the requirement whenever user creates an account definitely we need to create a duplicate account that is for sure but we need to stop this repetitions again and again so for that we have the solution called using a static boolean variable in trigger so we'll see how to do that as we already have written trigger on account we'll try to create a similar trigger on contact okay so contact contact trigger and object should be contact c-o-n-c-a so we have created a contact trigger we will do that in after insert so whenever a contact is inserted we'll try to create another contact in after insert logic okay so to do that we can actually write our logic something like trigger dot is i is after and trigger dot is insert okay now we need to write our logic to insert another contact okay however as we have seen in the previous uh slide we need to write our logic in a separate trigger handler okay so we'll create another trigger handler which is an epics class contact trigger android okay so in here we will write our logic so which is public static void create duplicate contact and here we should be receiving the list of contacts that are already getting inserted which which it will pass here new con list okay now we need to write our logic by running for loop okay this is called bulkifying of coding which we have seen earlier now so contact c-o-n new cons so if one record is inserted or 10 records are inserted our our code should be able to handle it so in here we need to create another contact cyn 1 equal to new coin contact and con 1 dot last name duplicate contact okay so now that we have given the name we will add into your new list and then try to insert the contact so contact coins two cons to insert so these are duplicate contacts okay so if one contact is inserted there will be another duplicate contact that's the idea so to start add and con one and finally we need to insert this to context okay now we have our method written we need to call this method from our uh trigger so after the insert whenever a contact is inserted after the insert we are trying to call our method which is this method create duplicate contact however this needs the list of contact that got inserted on so which we are sending trigger dot new okay now what happens here is as we have seen in the previous slides whenever a contact is inserted it will come here and then it will insert a duplicate contact as we are inserting another contact it will again call the after insert trigger which again it will call this after set and it will call this duplicate method and then another contact will be inserted and again it is getting inserted right that's the reason it will call again our trigger and it will loop on it will it be low blow blow group until it gives an exception so let us test that out first so we will record two contacts click on new and then i'll just create test one two three and then click on save it should give me an error saying let's see it is getting called these many times and it is giving an exception saying that tap exceeded so this is what recursive trigger mean so trigger is getting called recursively until this this is reaching a depth okay so to fix that we need to create a static boolean variable let's see how to do that so that's an easy thing basically we need to go to our class where we can create a new static boolean variable static boolean oh it's like is trigger ram okay by default we'll make it as fast okay now in our trigger we'll check so what happens is first time when it comes let's say first time a contact is inserted it will check whether it is insert or not if it is after insert we will check our trigger also that variable also so that boolean variable so we need to call the boolean variable by using class name dot that boolean variable so if that boolean variable is false which means if the trigger hasn't run yet only then go inside so what happens it will go inside and after it goes inside it will run the logic right so here what we will do is so we will change the trigger and value to true here so copy this and then make it to true okay now what happens is so for the first time whenever a contact is inserted it will check this condition by the time it comes for the first time this is trigger ran will be punch so as this is false false of negation will be true right so that's the result will go inside and as soon as it comes inside we are making it to true okay and then we are running out duplicate logic so what this duplicate contact logic will do it will insert the new contact with duplicate contact name okay and then we are doing the insert as we have done another insertion it will call our after trigger again so it again comes here but this time as we have done this value to true here it will say the contactor handle dot is triggered would be true negation of true would be false and then it will stop going into this for if if condition again so this is how by using this variable initially it is false for the first time it is coming inside we are making it to true so for this reason every time it comes again here or because of after insert triggers it will not go inside just because we already made it to true so by using the static variable we have stopped the looping of trigger basically we have stopped the recursive running of a trigger let's test this out so we'll go back again go here click new and then we'll just give test one two three and then clicking on save should create test one two three and a duplicate contact also so the duplicate contact name we have given it as duplicate contacts let's see whether it has created so i just need to check all contacts duplicate yeah you see all we have got created this is what we have right now logic whenever a contact is created we are creating a duplicate content the next best practice is use comments to make your trigger readable i think you already know this whenever you write trigger or any code make a habit to write the comments of what exactly you are doing in that particular trigger or in the logic if we take our trigger as an example we have written the comments respectively right so on this method so whatever logic that it is doing here we just added that in the comment section so that whenever a new developer or any other support developer sees this method they will understand what exactly we are doing in this method so make a habit of putting comments like this so let's say if you want to put some particular comment on a specific line you can just add it here saying that user user email address will be added into the list something like this so you can add as many as comments you want to make your trigger or your class more readable let us see few and three questions so the first question is what are the events in trigger so there are total seven events before insert after insert before update after update before delete after delete and after undelete we have seen the respective scenarios for each of the event but however to remember this even most of the time people will get confused whether it is before and delete or after and delete so the hint would be a 3 b 4 in essence 4 afters 3 before so you need to understand for insert update and delete you will be having all before and after but for under it only we'll be having only one which is after and delete so 4 is 4 afters after insert after update after delete after delete and three b's three befores before insert before update before delete now comes the second entry question what are the types of trigger so there are two types of trigger before trigger and after trigger and before we have seen in the previous entry question before instead before update before delete and for after you will be having four emails which is after insert after update after delete after delete and we have already seen the thumb rule whether how to decide before and after event whenever a requirement is given if the requirement is either to pre-populate any field on the same record or to fire a wearer validating the record then go with before events whether it is before insert or before update in any other condition in any other connection except these two scenarios if it is coming into any other scenario then you need to jump to after insert or after update events please do remember this number so that you most of your scenarios can be answered easily entry question number three what are the context variables in trigger so while we are writing the code we have seen these context variables so there are total 12 context variables which are trigger dot b is before trigger dot ease after trigger dot ease insert trigger dot ease update trigger dot ease delete trigger dot ease and delete trigger dot new map trigger dot new map trigger dot or trigger dot old map and these are the two that we haven't discussed in our scenarios but trill dot size is something let's say how many records that you have inserted from data loader or workbench if you are inserting a record from user interface this trigger dot size will be always one because from user interface you can only insert one record if you are inserting from data loader let's say you are inserting 10 records that trigger dot size will be 10 records trigger dot is executing so whenever you are doing some kind of logics let's say you are doing it in some kind of apex class kind of thing you need to understand whether that logic is being run by trigger or it is an standalone method then by using this trigger.executing you will understand whether that method is called by trigger or a standalone method so for that you would be using trigger dot new is a list which will be having latest value that user has provided it dot new map is basically will be having id key id value pair and old will be having the previous values before the user has provided the values same with old map which will be having the same kind of list but in the map structure which will be key id value pair enter your question number four what is recursive trigger recursive triggers are the triggers that are running on loop either are running recursively so basically a trigger is getting called again and again because of your continuous inserts or like the way you are inserting it or whether way you are updating it we have already seen such example earlier so how to prevent that recursive trigger so introduce my task how you would prevent it then you need to say that use static boolean variable to stop the trigger recursion into your question number five will trigger dot new context variable available in before insert event the answer is yes so what is trigger not new trigger dot new is nothing but the list of records that user inserted from user interface so basically you need to understand trigger dot new as the values that user will provide into database any value that is new to database or user provides it or like it's new to database some new values you are providing it there then those values are stored in trigger.new if you're not giving any any new values to the system those values will be stored in trigger.gold okay so trigger.new before insert anyhow you will be providing some values that is the reason trigger dot new will be holding the list of values or the stop records that you provide and then the answer is yes of course now the next question will trigger dot new map context variable available in before insert event the answer is no why because trig.new map is a map with key value pair however the key is id of that record but as this is a before insert event the record isn't inserted yet so just because it is not inserted id value will not be generated correct that's the reason in before insert because there is no ide salesforce will not have this trigger.new map to be populated so even though we have to dot new in before insert trigger.new map is not available because the key would be the id of record but id is not available in before instead that's the reason trigger.new map is not available so this kind of trick questions might come to you just don't get confused you need to understand whether id value is there or not because trigger.new map or old map will have id as its key value as it's the complete recorder let's create a thumb rule here so if any event is doing any new changes to the database let's say you are providing new values to the database then trigger.new will be available in that event with those new changes in this degree. okay so example insert event provides new values to the database right so whenever you are doing an insert you are providing new values to the database if you provide new values to the database then sql.new will be available so in insert event both in before and uh after insert you will be seeing trigger.new okay now in update even even update our event also provides some new values right whenever you're updating you're basically providing some new values overriding the old values which means you're also providing new values into the database hence sugar.new also will be available and both before update and after update now we will see the delete event delete event doesn't really provide you values to the database why because you are just deleting that record already existing data you are just taking it out from the database so basically you are not providing new data into the database hence share.new will not be available and delete event by using that thumb rule we'll try to populate this table so we have for the four of these context variables we'll see whether these context variables are available in all of our seven events okay first we'll see before insert and trigger new trigger new is available in before insert or not as we have mentioned before whenever you are providing new values to the database in in that event so then obviously trigger.new will be available in that event so in before insert basically you are doing an insert operation whenever you are doing an insert operation you are providing new values hence trigger dot new av is available in before insert now we will talk about trigger dot new map so trigger dot numeral pulse will be having the new values however trigger dot new map is basically having key id value of salesforce key as id value of salesforce so salesforce ids will not be generated before the insert of the operation as this is before instead salesforce id is not generated hence new map will not have the key value as i says force id hence new map will not be generated in before insert hence this is not available now trigger dot old or old map so if there is any existing value of that particular record only then trigger.old or old map is available so in before insert will not have any of the existing values hence old and old map is not at all available in before insert i hope this is clear for you now we'll talk about after insert even after insert is also something like you are inserting the record after the insert anyhow you would be having the new values hence basically you're providing your values to the sales force so into the database so you will be having trigger.new value is available in after insert now we'll talk about trigger.new map the difference between before insert and after insert here is it is after the insert which means once you are inserting a record into the system salesforce id is generated as salesforce id is generated trigger.new map will also be generated why because salesforce ids are being added as key value key in new map value as salesforce record hence trigger.new map is available in after insert same like before insert trigger.old or whole map will not be available because there is no existing values in the insert operation so after insert trigger.old is not available so trigger.old and trigger.old map is not available in after insert operation now we'll talk about before update operation so as i have mentioned in the thumb rule if you are providing new values then trigger dot new will be available correct so when you are providing when you are doing an update basically you are overriding the previous value and providing the new value right so let's say i change the name from srikanth to salesforce then new value is salesforce so trigger.new would hold salesforce value trigger.old would hold srikant value hence trigger.new is available as salesforce ids are already there so trigger.number also will be available for that record and old is available because the previous values will be stored in old list old map is basically a map of the old values so old map will also be available in before update so this is very much same with after update because after update also you will be having new values and old values too hence your dot new new map old and old map is available and after update operation all these four context variables are available in both before update and after update now we'll talk about before delete so before delete so as i have mentioned in the thumb rule if you are providing new values to the database only then trigger dot new is available however before delete basically you are doing a delete operation when you are doing a delete operation you are not actually giving some values or new values to the database hence trigger dot new will not be available so before delete and uh i mean before delete trigger dot new is not available so in the same way trigger new map is also not available why because it's basically if there is no new values there's no point of having either new or new map now we'll talk about old so as you're deleting the existing data so all the existing data will be stored in old and old map hence you will be having trigger.old and you also will be having trigger.old map now we'll talk about after delete so in after delete it's very much same like before delete only so in before delete you're not having the new values right in the same way after all delete also will not have new values you are actually deleting the existing data hands before delete and after delete will share same kind of visibility on this context variable so there is no new or new map in before and after delete will have trigger dot old and old map in before delete and after delete now we'll talk about after undelete after until it is something a new a kind of uh event here so basically you are undeleting or like you are taking some data from recycle bin so as you are taking that new data from recycle bin and then putting into database that would be added as a new data into salesforce hence as that is considered as a new record trigger.new and trigger.new map will be available in after undelete event however you are not actually having any existing data into that so hence still.old our old map is not available and after undelete so this is the complete chart so people who wanted you can take the screenshot of it so that it can be used for your future reference i hope this chart would be useful for some of you and let's move on to the next section let's close this session with final quiz okay so we'll see the questions if a opportunity gets inserted and don't fill the closed state then pre-populate it with the current database 90 days which trigger event you would use so as you have seen this is an insert operation that user is doing right so whenever opportunity is inserted if they don't provide the close date then pre-populate it with the current date plus 90 days so as you know the uh thumb rule to decide whether it is before insert or after insert you need to decide whether it whether you are doing a pre-population or validation of the record if you are doing either pre-population or the validation of that record then you should be using before insert not after insert as this is insert operation so we need to either choose before insert and after insert by thumb rule we have decided it is before insert so the answer would be before insert next question when an opportunity status changed to closed sending congrats email to opportunity owner which trigger you would use so when an opportunity status changed to close as they have mentioned changed change in the sense it has been a previous value before and now they are changing it to close which means they are updating the record to change the status to closed so as is an update operation so it has to be either before update or after update so by using this thumbnail we need to decide what operation it has to be or what even it has to be send and congratulate so this is not a pre-populating of record or it's not a validating of record so as it is out of those two scenarios we need to choose after update so here the answer would be affects trigger after update next question if user deletes an account delete all its shared records which event you would use so whenever account is getting deleted deleting of all child records so basically as user is deleting the account it's a delete operation it should be either before delete or after delete right so delete all its share records so whenever if you want to do any action other than providing an error or like validating of record you would use before events so here you are actually deleting child records so hence you can choose after delete so the answer would be epic trigger after delete next question in account record annual revenue value should never be empty how do you do it which events you would use as it has said which events okay so which means it can be a multiple answer too so annual revenue is a field on account record so it ha it should never be empty basically you should be validating the record saying that if every annual revenue value is not entered then you should be providing an error so when you would be giving the value it's like whenever you're do inserting a record or updating a record so if you are doing a validations then obviously it has to be before events hence the answer would be when before the insert you need to write a logic to validate the record and before the update you need to write a logic to validate that record so the answer would be before insert and before update most of the time as i have mentioned earlier whenever scenario comes it might be a single event you need to select or you might need to select a combination of events next question is in account record when annual revenue is greater than 1 million i guess this should send an email to account owner which event you should you should be using so whenever annual event is greater than 1 million so when this annual revenue can be given annual whenever account required is created they can provide annual value whenever they are updating the record they can provide the annual revenue value so it has to be both insert and update operation however we need to decide whether it has to be before or after so you're neither violating the record nor you're pre-populating an existing field in that same record hence it has to be after event based on our thumb rule so it has to be after insert and after update events next question is which of them are context variables in using trigger so try this one so tell me what are the context variables in using trigger so the answer is after undelete before update and after update there is no before and delete operation at all hint would be for a three b for after three before so there is no before undelete next question is how many triggers can we write on a single object 1 2 10 many the answer is many you can write multiple triggers one single object but recommended is one salesforce or allows you to write multiple triggers on a single object but the recommended recommended number of triggers on a single object is one can we call external system from trigger answer yes or no the answer is yes if you want to do an integration with external system or if you want to do a caller from the system you can actually do it from trigger triggers are synchronous call out has to be done asynchronously whenever if you want your code or callout has to happen asynchronously put your callout code in a future method and call that future method from your trigger so this is how you would do can we call a math class or cable class from trigger of course yes it's same like the previous scenario trigger source synchronous batch classes and cable classes will run asynchronously so that should be fine trigger will do that job and batch glasses and cubicle glasses will do its job in a separate thread so from trigger you can call feature methods batch classes and cable classes also so trigger dot new is available in which events so before insert after insert before delete after delete so based on our previous chart i think you people can answer it it a the answer is before insert and after insert before because before delete and after delete we are not having the new data provided into the database as per the thumb rule if you are providing only the new data to the database then trigger dot new will be available hence it's only before insert and after delay after insert trigger dot only is available in which events i think you can guess it right it's the opposite way so it's before delete and after delete because before insert and after insert there is no existing values if you provide new values that will be stored in trigger not new if there is any existing values then it will be stored in trigger.old or old map respectively and that's the wrap up if you have any questions comment down below practice practice practice and bye
Info
Channel: Salesforce Exclusive
Views: 182,842
Rating: undefined out of 5
Keywords: Crash course on Apex Triggers Salesforce | Complete guide with Real time scenarios, apex triggers salesforce, salesforce triggers, triggers, triggers with real time scenarios, triggers interview questions, salesforce apex triggers, before and after trigger events, how to decide before and after trigger events, trigger context variables, salesforce trigger events, Crash course on Apex Triggers Salesforce, Complete guide with Real time scenarios, apex triggers, trigger best practices
Id: pjxJ2oR4ZNs
Channel Id: undefined
Length: 155min 4sec (9304 seconds)
Published: Tue May 03 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.