foreign [Music] welcome back to another explained series video and this video is special this is about Apex triggers and we'll be talking about Apex triggers we'll be understanding the basics but more importantly this explained series will not be just one video this will be 30 videos after today's video yes that's correct we'll be talking and we'll be doing live 30 use cases on triggers that will help you understand and make decisions on how to use triggers where to use them when should you use the before context when should you use the after context and all the major decisions you have to take with triggers uh you can you can figure that out yourself very easily after you go through these 30 use cases these 30 use cases are different every use case is different and I have tried to cover as much as scenarios as possible but today we'll be talking about Apex triggers understanding them and then from tomorrow for the next 30 days you get to see one use case each as a separate video me coding it live in front of you and talking uh talking it through you so that you understand how my mind thinks about triggers and how do I solve a use case how do you actually figure out how to go about solving a problem right so that's about this particular explained series today's video will just be about triggers as Basics this is going to be a long one but let's let's get started all right so Apex triggers first of all let's understand what are Apex triggers for for anyone who's from the admin background and has not started off development or someone who has started off development but is not completely sure of how to go about it and where to start triggers can be a good point to start if you if you know uh the order of execution and you want to write any kind of logic uh as soon as you save a record triggers is the place where you do that right so Apex triggers as the name suggests act like trigger points right to perform custom actions before or after any changes that are made to Salesforce records now these changes can be insertions updations or deletions right now if I were to take you to Salesforce and if I were to open an account record right so when I go to the account Tab and I click on the new button what am I trying to do I'm trying to create a new record right let's say I fill all of these values and I hit the save button what really happens a record gets saved into the database right now as soon as the record gets saved into the database you might want to do things before it is saved and after it is saved right similarly let's say you have a record you have created Burlington textiles and you want to modify this record right so when you hit on the edit button and you make some changes to the fields you might want to do things before the record is saved or actually saved to the database and after it is saved to the database right one one simple example would be if as soon as I save my record I want to send a notification to the account owner saying that the rating has changed right or let's say I want to send out an email to my customer saying your annual revenue has changed right and if I create a new account record or a contact record I can send an email to the admin saying a new customer has just signed up in our system right so where do these where do you do these kind of activities you do them on trigger actions right these are the trigger points you use and for using these points you have to use Apex triggers right and primarily they work with the credit operations it could be an insertion updation or a deletion there's one more use case but but primarily you would use it for these these three things okay now you can even run a trigger when a record is restored from the recycle bin I hope you know you can delete records right and when you delete records where do they go they go to the recycle bin right you have something that's called a recycle bin here so as soon as you delete any kind of record that goes to the recycle bin and you can I'm so sorry this is my auto correct so if you go to the recycle bin you might have a record here and if you see a record and you want to restore it right you can restore it from here and you can have a trigger perform some actions on this event also which means if you want to restore something or undo a deletion even that can be tackled through triggers right that's the other use case apart from these three cool so triggers are available on object level so you can write a trigger for every object so you would understand how do I write it for for who do I write it it is basically on an object to object basis so if I want the opportunities and I want to modify something based on how opportunity is saved I would go to the opportunity object and I can create a trigger for the opportunity object okay so you see the triggers option is here and this is on the object level so every object has a different trigger right you write a separate trigger for every object now all triggers are bulk triggers by default which means they are capable of handling multiple records at a time always write triggers keeping this in mind so what happens normally is if if I were to go to this record and modify it and I where to write a trigger on it would I want to write it on for just for this record what if you do a data input right what if you do a mass update in those cases our trigger should be able to handle multiple records at once so Salesforce triggers provide you the capability because they are bulkified in general right you get a you get some variables that are already bulkified so they are called bulk triggers they don't handle one record at a time okay so every time you write a record you your code should always be intelligent enough to process multiple records even if the use case is let's say that's you know one record at a time you should always attempt or try to handle the trigger code in such a way so that if multiple records come into the picture our Apex code or rather the trigger code is capable of handling that all right so that's about the triggers introduction now an important point we have been talking a lot about low code and no code automation right that is process Builders flow automation flow Builders uh creating sites and all of it but why would we write triggers over process Builders and flows right Salesforce has been promoting flow Builders like anything and looks like everything needs to be shifted to flow Builder so that we can achieve as much as automation we can but why do we need triggers and when would you when should you go about using triggers and not processes and flows right now there are some use cases where you would need triggers if you are familiar with flows and process Builder you will get this easily or else it's okay you can just uh be with me and then I'll help you understand so with triggers you can handle before events not just after events okay so with process Builders you cannot do that right process Builders you can do as soon as the record is created or a record is created or edited right that means once the action is completed that is when you can hit the process Builder but what if you wanted to do something before it happens right we'll talk about the order of execution very soon but before events can be handled in triggers they can be handled in flows as well but process Builder does not let you do that right so if you want to handle before events you can go with triggers or flows next thing is handling exceptions and showing user relevant errors instead of generic errors right now with process Builder and flows we get an unhandled fault exception maybe some issue with the flow maybe the fault path uh is shown or the process Builder failed so we get a very weird error a very long error that shows the entire trace and the and the message is very much non-user friendly and non-user readable so if you want to handle exceptions well you can use triggers right and you can handle then by showing them generic instead of generic errors you can show the messages that are relevant to uh understanding what the issue was so you can use the add error method and you can show exceptions and you can handle them right you can even create custom exceptions and you can show them to the user through triggers all right next is handle delete and undelete event so you can handle deletion and undulation events as in let's say you want to restore some information from the recycle bin and you want your admin to know that you know five records were restored can you do that from process Builder no you cannot so you can do this from triggers right handle complex custom logic that cannot be easily maintained and managed by automation now you might have a use case wherein you have 15 countries 84 price rates 34 Price Books or a good catalog of products and you want to handle some level of custom logic that that has to work with different profiles in a different way understand creating decision nodes on the flows creating those nodes on the process builder at the if else if ladders it's it will be very complicated it will be very cumbersome and it will be difficult to maintain in future right the versioning and the maintenance will be a pain right so it's better to move any kind of very complex custom logic into triggers and this is where you can handle it a bit better and you can maintain it all right additional validation checks that you can that you want to put to avoid bad data you can put it here like we said we can handle before events right so before the record is saved we can check if the data is correct if the data does not contain any discrepancy any any issues so we can show an error we can we can do some validation checks before the data is committed into the database that can also be done from triggers right now partial success is allowed in triggers but not in processes which is more of an all or non-con not none framework right if your process Builder fails your entire transaction is rolled back you you cannot get you don't get to save a specific record or if you if you have 10 records you want to save one of them failed your processes don't let you save the other nine records but you can attempt this on triggers you can have partial updates or partial success can be achieved and can be set up in triggers that's also something why you would want to use triggers over process and flows all right so now let's begin and let's talk about the trigger Basics we will try to understand the framework okay so there are two primary or rather two general trigger type trigger types one are the before triggers and the other one are the after triggers so before triggers are primarily used to update additional values to the record or validate them before they are saved in the database whereas after triggers are used to update the related or unrelated records and do any kind of post processing after the record is saved to the database right so the difference here is that that before the record is saved on the database if you want to do any operations you do it on the before triggers and if you want to do that do any kind of processing or any kind of related stuff in the trigger after the record is saved you do it here right these are the two primary types of triggers not types but rather the two ah broad division wherein you have before triggers and after triggers all right let's quickly talk about the syntax so the syntax has trigger as the keyword you put a trigger name and then you write on so you say trigger account trigger on account object so you have the API name of the object here and then you mention all the trigger events and under this particular block you add all your code right now trigger events are comma separated events that need to be invoked through the trigger all right let's quickly go to Salesforce and let's create a trigger here so I am on the developer console so in order to create a trigger we go to file and we click on the new button and you have all the options available here you can create lightning components visual Force components or Pages Apex class and then you have Apex triggers right so when I hit on the Apex Trigger you get an option to give it a name and select an object like I said triggers are on object level so you have to give it a name let's say contact trigger and then I can choose the contact object here this one right here and I say submit right as soon as I do that you see the same syntax pops up automatically it says trigger name of the trigger on keyword and name of the object followed by the trigger events now if you see by default Salesforce gave us one event that is before insert right but this is nothing but a set of comma separated events I can say after insert also after delete before update I can put all of those events we'll talk about this events very soon but this is your comma separated list of trigger events that you can use right and this is where your trigger code goes right all your trigger code will be here okay now this would be on the contact recorder let's go back to our screen and let's see what's here so note that database changes are automatically rolled back if trigger does not run successfully so any kind of database changes that are done they will be automatically rolled back if the trigger is does not run successfully right you might have set the partial partial thing to true in that case partial rollback will happen and some records might be saved but by default if you do not use that concept the database changes are automatically rolled back okay so let's say you are doing a transaction and you and you hit the save button but the trigger fails somehow the record will not be saved into the system and that you have to create the record again that is what it means right that is what role backing is okay cool now let's talk about these trigger events that we were trying to figure out here right this section right here that is the trigger events if I take a look at all the events you see that you have something that's called before insert before update before delete these are your before triggers right we talked about the two broad categories right before triggers and after triggers so so you have before insert before update and before delete similarly for insert update and delete you have after insert after update and after delete what does this mean this means before a record is inserted into the system do things here before the record is updated make changes here before the record is deleted stop them from doing that after the record is inserted send an email after an update is done to the system update the child records also after the record is deleted notify the owner of the record and then you have one more use case which was our recycle bin concept this is your after undelete undelete is nothing but restoring deleted data right so you have something that's called after undelete and this is not available for all objects it is only available for some objects we can refer the documentation for that okay these are all your events that we will use and this pretty much cover all kind of operations that you have you are covering insert operations update operations delete operations and undelete operations and both before and after now you might think why is there why you do why do you not see a before and delete because before undelete is not something that can be predicted can you say when would a record be restored you don't have a you don't have a time frame for that right after you restore a record is when you can say okay I undeleted it right but you cannot say that before before undeley does not exist because it it is not something that can be predicted by the system right no one can predict when you would undelete it right those were all our events and if I were to write them here if I show you here you can just say before insert before update before delete after insert after update after delete and then after undelete and when I hit the save button this should save successfully because all the events are accepted right now if I write something like before undelete let's see what happens and say save so you see I get a problem here and it says bigger usage before undelete is not supported so this is something that is not supported by triggers so we can get rid of this and we can say save again so this becomes your comma separated list of trigger events all right I hope you understand what the event is here before insert that's the event the insert is the event and when is the context it is the before context similarly you have after update when is the context you have after the record is updated all right next let's take a look at what kind of context variables we have when we are using triggers right now like I told you triggers are already bulkified in nature right they are bulk triggers they don't work on one record they work on multiple records together so how do you figure out in in this particular code snippet here right how do you figure out which event what do you want to do on on what event you have all your events available here but you want to do X when before insert happens let's see right you want to do y when before update happens you want to do Z when after undelete happens how do you distinguish all of that inside your code here right so for you to be able to understand whether the contact is context is before insert or before update you have some context variables available that help you decide what is the current context that you are in right when I say current context how would this work if I go to the contacts list here I click on the new button and I create a record let's say okay I see himanshu maheshwari and let's say I click on the save button what am I trying to do here I am trying to create or either insert a record correct so as soon as I hit the save button I the Salesforce will internally check do I have an event for insert it will see okay I have before insert and I have after insert so I have to take care of these two actions now but let's say you have to do J when after insert happens now you have two things before insert and after insert right how do you figure out which event and how do you segregate that thing so for that you have something that's called context variables context variables come from the system.trigger class right so you'll have to use trigger dot with them so you have something that's called is insert what does that let you identify this tells you if trigger dot is insert two insert activities here okay so this is more like a Boolean flag from the system.trigger class this is the system.trigger class that we have already and we can use this context variable to help us understand okay is this an insert activity it will be true if it is an insert activity likewise else if it's an update event you would assume that you have an update is update Boolean right yes we do so we'll go to the context variable and see that we have in is update variable all right similarly we have is delete that lets you identify okay this might be a delete operation then I'll say do update activities here and I'll say else if trigger dot is delete do delete operations here right this is how you are bifurcating all the context but as of now what you have done you have bifurcated the credit operations insert update and delete how do you bifurcate the before and after activity also you have a context variable for that so you have something that's called is before is after is undelete right okay is under lead is a credit operation so these four are your credit operations and then you have is before and is after so let's say in our use case in our current use case we are only working for an insert scenario let's say right I get rid of the update and delete scenario I get rid of all of these extra events right let's say this is our only use case these are the two events that we need to work on I'll save it here right so I have to do my insert activities here and in here I can simply say if trigger dot is before another context variable I'm using I'll say do before activities here right and else I can say do after activities here make sense so the else will run if it is not a before context if it is an after concept context do you want to test it let's test it so I'll put a debug log everywhere so that we can see how things look like so I'll say inside insert scenario okay and then I'll put a debug log in the before and the after context inside before scenario and then I'll put a debug log here saying inside after scenario all right now let's see as soon as we create a contact record what really happens okay I'll get rid of these extra comments okay so this is my current trigger and I have only two use cases one is for before and one is for after and that's only for the insert right let's go and let's enable my debug log and let's open the debug log window and here let's see if we get a new log when I create a contact record okay so I'm just putting in the mandatory field values and I'll hit on the save button so now this says contact is created let's go back to the debug log and I see a new log created this one right here right this is 5.9 KB probably this is the one so you see contact trigger on contact trigger event is before insert right now if I hit the debug only tab I see inside the insert scenario inside before scenario inside insert scenario and inside after scenario do you see what happened first it executed the before context that is why it came in here it found that you know we have insert events available so what would it execute first it would go inside here it would evaluate to true this insert is evaluated true it gave me this debug log right and then it checked whether it is a before context or an after context it was before so the before one runs first so it executed this one after the before triggers ran it went ahead and wanted to run the after insert so it came back here again and it's checked whether the require whether the context variable is insert yes it is insert but this time it went back and went to the else condition because it was it is it was the after context this time so you see inside insert scenario then before and then this lock comes again and then after right so the code traversed this particular block two times and this one once and this one once which kind of tells you the trigger runs the before context first and the after context later right that is what is here right you see four then six then four and then nine so it's four this is four six then four and nine all right what if I have this code but I do not have the event declared here what happens then let's refresh the code will save a file right but now only before insert is defined now Salesforce will see what happens let's click on this uh clone button and let's create another record and if I create himanshu 1 and say save and take a look at the developer console this time let's I opened up the wrong console log let's open the 4.1 kb1 right now if I go to the debug logs let's see so you see I see only inside insert and inside before scenario why even though you had the else condition there but you did not declare your event if you did not declare your event Salesforce does not go inside and work on that event you have to have it here for your code to be executed for that event this is mandatory okay so if you have after insert only then this code will be executed or else it will be completely ignored because you are trying to tell them I want to only work on this event no other events I need to focus on so it does not even care what else you have written in the else condition it will just check okay insert before it will just do this it will come back here but it will not execute it again because after insert is not mentioned make sense so this is how your context figure works context variables work what are the variables we looked at we looked at before and after variable and insert update and delete now there are two more rather three more yes new old and size so like I said trigger is already bulkified so if you are working with one record you can check trigger dot size it will show you one but if multiple records come in come in like through an import or a mass update or a mass delete then trigger dot size will vary okay let's check what is the trigger dot size here let's get rid of all of these six so if I put trigger dot size here I can use something like this trigger Dot let's save it right trigger dot size is saved and I'll just put a space here and before insert is there let's see how many records come into the transaction when I create one record it should give me the size of the trigger or rather the context how many records are showing up so I have the same one shoot two and say save so I created one record let's go and see what is showing on the log let's open this log right here and this should show me inside insert scenario one so I have one record here right and if it was a bulk scenario wherein you did some data input or something the trigger dot size would vary based on whatever the number of number of records that come into the picture okay but if you have to check you can use the trigger dot size for checking things like you know to avoid any kind of Governor limited issues you can do that but this is one variable you can use okay you can segregate your code like this if trigger dot size is equal to 1. right ah you can say do this operation you might want to do things differently to this operation and if it is more than one then you want to do it differently correct so that's where you can use the trigger dot size okay now every time you're on the trigger you have two variables trigger dot new and trigger.old these are an other another two variables that you get right developer console does not let you align things by default so I'll just say old save okay I think there's an extra bracket let's get rid of it and say save again so right this is saved now let's give it a relevant tag name new record and let's give it old record here okay I'll show you something save so these are two more variables that you get from triggers okay let's see what happens now when we create a record if I click on the Clone button and if I now save the contact record and say this got saved successfully and if I go back here and I take a look at the logs and if I say debug only you see under the new record I get the entire record that's created all the field values are there and it holds the value that I have put in the record right see himanshu 3 maheshwari everything else is null because I did not put anything else salutation is Mr Right this is your new record which is nothing but the trigger dot new this variable holds whatever you are inserting right now the new information that you are inserting but now let me ask you something trigger.old is something that will hold the old information right when does this when does this come up come in the picture let's say I don't want to have the insert context I want to have the update context right and if this is is update I would say show me trigger dot new and show me trigger dot old values okay now if I go back and I edit this record because I want to do an update scenario right let's edit this record and let's put a title let's put architect right and I'll say save so I'm updating the record do I have an update context yes before update is there and this will run true because I just updated so it should give me the debug logs right let's go back and let's open the debug logs so I have 6.79 KB debug log and let's say what's only the debug only now take a look at these two records right you see this is the new record and this is the old record what is the old record let's take a look let's take a look I don't see the title information coming up because that's uh that's longer than the text that it is supposed to show so what I can do is let me modify something that's here on the top let's modify the salutation okay let's go back let's close this lock first of all let's go back and now let's go to details and I'll just change the salutation and I'll change it to doctor all right I'll say save now let's take a look at the debug log I made an update right I should have a debug log yes I do 6.2 KB let's open this debug log and now let's see the salutation on the new record is a doctor and the salutation on the old record is Mr which means which means you get to work on two different versions of your record the old version and the new version and this is what these two variables are for okay the trigger dot new will hold all the information that you are currently committing to the database which is new the changes that you have made whereas the trigger.old will hold information that was there before you made the change so in case you want to make some kind of if conditions you want to understand whether our specific value has changed or not all of those kind of operations can be done we look at how to use these two variables and there are two more variables which are maps of the similar concept but we'll understand how to use them okay but for now just understand new holds the new information that you just committed to the database old holds the information that was just prior to what you prior to when you made the changes okay now an interesting thing to note when I use the is insert scenario and I was just using this event here right we saw this log and it had new information but old information was not there it showed us null null is nothing but empty basically no no information why was the old record null because trigger.old cannot hold any value if you are inserting a record understand this when you are creating the record for the very first time will you have an older version of it no you will not right which is why trigger.old shows null when you are using the insert scenario and you can have have values on the trigger.org in the update scenario or the delete scenario right so we will see how where you have these records and where you can use this variables the variables are available for different context or different events and they are available for specific reasons we will take a look at that map also for now just understand that trigger dot new holds the newer information that you commit and the old variable holds the older information ok so those were the context variables I think there are two more variables I did not mention here which is trigger dot new map and this is trigger.oldmap so you have new map and old map also so these are nothing but the trigger dot new and the trigger.hold old holds a record of type object right but if you want to store a map you can you can use the same using a map let's see what's the difference now I have before insert and I have is insert check here let's see what does the new map show us if I go ahead and say clone and say save I just created a new record so I should see a trigger.new map value but that would be a map that would be of type collection map okay and it comes in handy when we are doing comparisons we'll take a look at that also very soon when we do our use cases for now just understand that we have these so the trigger dot new record shows null as well which is weird let's put after insert also and let's see if I can get you the information from the new map let's close this and let's go back let's clone it one more time on shoe five let's say save okay let's go to developer console let's see if I have a new log 7.23 I believe we have information I don't see yeah so you see the new map and the old map is not available in the before context right so the new map and the old maps are not available on the before context but under the after context you see that something new has been added and that is being shown on the after context you understand why you see two the same logs twice because it is running the before context first it came in here is insert it ran the before context then it came back and saw okay after insert is also there I have to execute it one more time for the after scenario and that's when it found out that new map has a value it does not hold anything in the before insert and if you see the new map is nothing but a key value grid wherein the key is the object ID the record ID of the object and the value is the entire object itself okay so if you see this 0 0 3 ending with double 80 is nothing but this particular record ID of the record this particular record ID 0 0 3 a80 right and you get this entire record as a value of this particular key and you get it on the after insert record so you see the variables differ and play different way play different game when when you change the context and we'll understand this entire grid of where which variable fits into the picture where would a variable be used and why would it not be in a specific scenario we'll understand all of it in in in our later later part of the video okay we'll make a grid of where to use which variable cool so that was about context variables and pretty much everything you would want to use and play with when you are writing triggers this would be your entire game let's understand some considerations we have so you cannot use DML or rather the database operations on trigger.new and trigger.old you might be wondering okay trigger dot new holds the contact information what if I make an update to that variable itself no you cannot do that okay trigger.old is always read only and we can't make any changes on top of it because trigger.old holds the older value right and you just have it to understand context you cannot play with any and you cannot modify it even if you modify it where would you save it because now you are saving the newer version the trigger are new information right so trigger dot old is available for you to understand things and check things but it is always in the read-only format which means you cannot make any updates to the trigger.old variable or the record that it holds okay now we can use trigger.new in before context to update values but not in the after context trigger dot new holds a value for in our case it hold it held the contact information now let's say before I want to before I let's say I put one more check here I say if trigger dot is before right and here I want to update contact record shipping address I can do that here without writing any extra database operations but if I want to do the same thing is in the after context trigger trigger will fail it will not let me do it because the trigger dot Nu becomes read only in the after context it does not let you do any update operations here okay because the difference between the before and the after is right at this point the database come it happens the record is not completely saved and the transaction is not completed but thus commit is saved that thus the record is saved into the system uh and and it is a copy or an instance is created so you cannot re-update it here okay you can do things here like without writing any database operations you you can do things like you know contact dot address equals you can you can make some changes here what will happen is because the record is getting committed somewhere here you are being allowed to make changes here and add some values or remove some values or do those kind of things but as soon as you do your commit which is which happens somewhere here we'll understand the order of execution which here's which which happens here in the after context you cannot again update the record one more understanding of how why this is not allowed is let's say Salesforce let us do this right Salesforce let us update contact here okay now if the contact is updated here it will again go back to the trigger and if I have an after update scenario right it will run the after update scenario and it will come back and it will it will keep on going into a loop there is a chance that this might run into recursion or it might run into a loop right so it is better Salesforce prevents this and does not let us do anything in the after context it makes the record read only you can only use the record to mess with or play around with other records so you have the contact information but you can fetch the child cases and you can make changes to the child cases that is something you can do but the same record that is in the current transaction the contact record this record cannot be modified you want to do that kind of modification do it here on the before context that's why the before context exists do not do it on the after context that is a bad practice that's not a good practice and that might lead to recursion and that is something that Salesforce will not allow all right cool let's get rid of all of this code that makes no sense right all right I hope you are you're following me if not um uh Slow Down the video If or else go back a few slides start again from here but yeah this this should help and uh help you understand but we'll understand it a bit better when we do actual use cases okay every every use case I'll explain you why I'm why am I doing things why did I choose this variable why is this value showing this this by this kind of record everything we'll discuss okay with practical examples cool now comes order of execution so order of execution is basically salesforce's way of governing how a record will be processed into the database there are n number of things that happen behind the scenes we'll look at what what all happens and in what order because if you do not have a governing order how do you understand what will run first what will go next there are different tools right you have process Builders you don't have workflows now but you have process Builders flow Builders you have the before triggered flows you have integration jobs you have a post processing email templates you have approval process you have a lot of things cases entitlement lead processes sales processes duplicate rules matching rules lot of things right you have triggers which goes first what goes next there has to be a there has to be an execution order and this is basically the order of execution we'll Now understand the before and after context and it will be very clear to you understanding how Salesforce really goes with the order of execution now as soon as you hit the save button what really happens behind the scenes is basically what's told here and here I have taken an example of when you are making an update to the system right now when you are making an update to the system you have a record in the system already which was inserted some time back right now when you have the record in the system that original record is loaded from the database and whatever are the old values they are overwritten with the new values the new values that you made changes to okay that overwrite is done now if the required is request is coming from a standard UI page what is the standard UI page a normal page layout where we create the uh Records right this page layout if I click on this edit button this is the standard UI page right and if I click on the new button on the tab that is the standard UI page if a request comes from this particular screen these kind of screens what happens it checks for the layout specific rules we can configure page layouts right we can set fields that required read only we can do record pay checks we can do all of these things right and then any kind of metadata information like you know the field format is correct or not what is the maximum length that we've put on the object field level any field definition uh value uh discrepancy has happened or not all those checks are done and if there's an issue a Salesforce shows it on the page itself but if the request is from a custom source a custom source being a custom component a custom controller a custom flow screen it only checks for the foreign keys because these these rules don't don't matter here right they will only matter if you are going from the standard uh layout page so here it only checks for the Integrity or rather the relationship if the relationship has is at fault it throws an error or else it lets you go ahead now if multi-line items are created only then custom validation rules are run what are multi-line items this could be for the code code line items this could be for the opportunity opportunity line items right those product line items if they are created only in that case the custom validation rules that we have written are run here or else they are not run here we can just ignore this for now okay because this is just for multi-line items now as soon as the record is entered it has entered into the system without any issues the before record triggered flows execute now this is something relatively new in Salesforce but you have record triggered flows and you have both before and after recording at first which means you can trigger a flow in before context and after context process Builders do not let you do that but flows let you do that so this is the very first thing that executes your before record flows and then you have something that's your before triggered so all your before triggers run here this is what we are working on okay and this is where we got those two debug logs right before insert and before insert uh the insert log and the before insert log because this ran first in terms of the order of execution okay once your before triggers are run the system and the custom validation rules run any kind of system rule is there or any kind of custom validation rule that we have written they run here and if there's any issue it is shown on the screen if no issues keep going now you have duplicate rules and if there is a issue with the duplicate rule then the data entry is blocked and it says that you know a duplicate exists or else it goes and you know lets you ah proceed now once you are before triggered before record flows are run before triggers are run all the before triggers right which means every objects every before trigger will run not just one objects every objects based on whichever record is getting inside obviously let's say you are inserting opportunity record then all the before triggers for the opportunity record will run okay then the duplicate rules and if everything is good that's when the record is saved to the database it is not committed yet my language was incorrect it is saved to the rest the record is saved but the transaction has not been committed yet right commit is the final final hammer on the stone right that's not done here but it is just saved to the to the database and once it is saved this is this is the point if till which you can make any changes to the record that you're wanting to save but after this your new context becomes real only because this is where you run your all after triggers and this happens after it is saved to the database right not committed yet obviously but saved to the database so Salesforce does not let you make any changes to the context again because this is where your after trigger is done the before triggers are here and then you have the after triggers here which is why we saw four debug logs inside insert scenario inside before insert inside insert scenario inside after insert two logs from this guy two logs from this guy once all the after triggers are run that's when you have all the assignment and the auto response rules that run if there are any and then you have workflow rules uh now we don't have to worry about this section at all because this is retired or almost retiring you have escalation rules and then you have all the processes and flows there is no guaranteed execution of order order of execution with the process Builders you have written multiple uh builders that you have so there's no guaranteed order here and then you have your after record save record regard flows you remember what we did before it was the before record flows and this is where your after record triggered flows run the after record sequence then you have entitlement tools and if there is any kind of roll up summary or a cross object reference you have to update the parent record also right so that is done here after all the current records information is done the parent record is updated here and if let's say your parents parent also has some sort of roll up and some sort of cross object summary then your grandparent record is also updated okay what happens next you have the criteria based sharing the sharing rules execute right towards the end and once the sharing is sorted you commit the record to the database this is where the final commit happens and this kind of tells you that the transaction is completed so anything that has been postponed like you know sending email any kind of asynchronous jobs any kind of future methods that have been written they are done here as a separate transaction okay so this is your entire order of execution and the important things here are on green execute all before triggers is where you save uh you write all your before triggers before the record is saved and after the record is saved but not committed yet you do the aftertickers right and this sequence is important you uh for for an interview question it is important that you know that the record triggered flow runs first the before triggers run then the after triggers run after that and then the after record triggers run here and in between you at the process and flow Builder flows ok so now you understand the before context and the after cons context all all these uh all these jargons and the keywords I'm talking about is because this order of execution is maintained by sales source and you cannot play around without change it okay now it's important to understand how do you decide what to write on which event you have before event you have after event now where do you write what kind of things right for example I told you you cannot make changes to the same record in the after context so if you have to add any information add any field values to the record where would you write it it is understood you would write it in the before trigger right so use before triggers when you want to set some additional values to the record that's getting saved or if you want to validate or avoid bad data in the system and throw some errors to the end user so when can you when can you show the error to the user and not let the record saved into the system in the before context because when you're in the before context the record is not safe to the database yet so you can tell the user your record does not match a criteria we are not going to save it please uh fix it or create another record where do you do it you do it on the before context right similarly if you have to set some values on your current record you do it on the before because Salesforce does not let you do it on the after context right so now what do you do on the after context in the after context you want to do any kind of DML operations on related or unrelated records now for example as soon as an opportunity is updated and the stage is closed one you want to notify all your users that hooray we have one opportunity this is the revenue that we generated and you also want to create a task for the opportunity owner and tell him to congratulate everyone in the building right so these two things you would do when would you do them you would do them on the after trigger you would create a task record here as a related record and you would also send an email so you can do any kind of post processing logic like firing platform event sending out emails in working flows calling third-party systems why are you doing them after because you are kind of sure that the record is safe to the database everything in the before context ran properly and the record is going to be into the system so everything that I have to work on after the record is saved I'll do on the after trigger concept okay one example being the opportunity uh being one right so this is how you would decide before or after but don't worry we'll be doing the use cases and every question we will understand why are we going for the before context or after context okay the next thing is the trigger grid the cheat sheet that you need so this is what I was talking about wherein we'll figure out what kind of variables are available where so you have all of these events right before insert before update delete after insert after update after delete after undelete right let's let's try to figure out if we are allowed to use the ah grid values or not right if if we will not be allowed to use them Salesforce will throw an error for example before context right we saw that the trigger.old give us gives us null right but that was on the insert context let's do something let's go to Salesforce let's go to the developer console and let's start with before insert so I'll say if it is trigger dot is insert and instead of writing an if condition inside I can do it on the same line how I can say if trigger dot is insert and Trigger dot is before so this would be my before context okay and if I say system dot debug trigger dot new and I say save this should let me save it right what if I say trigger.old and I say save so this saves as well but the value will be null here right so I won't get any value so what we have to do is we have to try doing this and we can populate this particular grid that I have already populated but I want you to go to developer console and do this for every event and see what the debug log shows okay and that's how you can prepare this grid and you can understand okay after insert I have both I have the trigger dot new but I don't have the trigger.old after update I have both right before update I have both right and it's so if you notice the triggered old is available in both the before both the update scenarios this one and this one the trigger.old is available right where do you not see the trigger dot new you don't see it on the delete scenarios the trigger.new is not there in the delete scenarios right so you can figure that out once you you know Try It Out by putting a debug log and you create a record you can just practice this one with one one record okay and if you see a value null you can just say that you know you won't have the value for that particular event okay you can use this Grid or you can try it on your own and you can just prepare your own grid trying it on your own will help you understand okay I am not seeing this variable yeah that makes sense because why would it be available here in this context does not does not make sense right so that way it would be helpful so this is your event versus context grid it might be that some of the values are wrong here so I'll encourage you to take a look and try it out yourself all right cool what's the next thing the next thing is a very important consideration best practice you can even call it whatever you want so one trigger per object why is that if you notice we the order of execution said all the before triggers and all the after triggers now for example for the contact object you write five triggers and every trigger has the before insert context let's say you you make five files similar to this five different files now how do you expect Salesforce to understand which file to run first and which to run later there's no way right and then Salesforce also does not give you a guaranteed order of execution it will run file one first file five second file three third and so on the next time that you run the transaction it might change the order because it's not giving it a number based on what you have written it does not understand if you write trigger contact contact trigger one contact trigger two it doesn't understand all of that so the order of execution cannot be guaranteed if for the same event and the same object you have multiple files so it's better to avoid something like that why to create discrepancy if if that might go wrong right so it is ideal that you have one trigger per object okay and this is because if you have more than one triggers per object Salesforce does not guarantee the order of execution and in this case there is no control over which one can execute first so in order to avoid this discrepancy in code always write one trigger per object and host your events in that trigger code what's the problem of writing all the events here you can simply do things like this trigger dot is insert and Trigger Dot is after right similarly I can have same blocks for all my other events so I can just say this would be update right this would be update and then I have delete right so is there a problem of in terms of Maintenance no is there an issue with having all the events on one file no and it is easy to maintain yes so why not do it why create discrepancies without any reasons right and it is important that I mention all the events here only then it will run those blocks or else it will not write we saw that available so I would have all the events here is there a problem are we consuming extra resources just by declaring events no we are not doing that so we can go ahead and keep all of them here and whatever you need you can just execute that block you can just create the blocks and you can execute save right the file saved and everything that you have to tackle you can tackle in individual sections cool which is why you want one trigger per object right so that was all about the trigger Basics and now we'll jump into 30 scenarios use cases or rather live trigger examples 30 of them each one is different I have all of these use cases here and we will work on all of these use cases one by one a video every day right and that will help you understand triggers and I would encourage you to sit with me and try to write the same code by looking at the screen trying to figure out okay did I make a mistake did I declare the variable wrong is my context incorrect is my event incorrect did I miss something out and try to test it and understand okay this is how the trigger is working this is how the execution is happening this is why I use this variable and this is why I use this context all right and finally we'll actually be solving 30 use cases all right do do prepare this grid yourself and that will help you understanding trigger context and I'll see you in the next video with the very first use case that would be use case one from trigger and that would be posted on December 2 right so until the year comes to the end we are doing trigger coding all right that's all from this video of triggers explained series I'll see you in the next one till then bye [Music] thank you