AFTER INSERT:
This event runs the block of code after inserting data into the
database. Operations such as creating or updating related records can be
performed under this event.
SYNTAX:
trigger triggerName on objectName (after
insert) {
// Block of code
}
SCENARIO:
We are having the requirement to insert dummy Contact record
as a related object on Account when the Account record is created.
APEX TRIGGER:
trigger AccountMainTrigger on Account (after insert) {// Specifying the event.
createContactClass obj=new
createContactClass(); // Declaring
instance of the class.
if(trigger.isafter &&
trigger.isinsert) // Using
context variables.
{
obj.method1(trigger.new); // Calling apex class method.
}
}
APEX CLASS:
public
class createContactClass {
List<contact> conList=new
List<contact>();
public void method1(List<Account>
accountList){ // Obtaining
the list of Account records from trigger.new.
for(Account obj:accountList){ // Iterating over account list.
contact con=new contact(); // Creating a contact instance.
con.FirstName='Testing contact'; // Creating contact record for each account
con.LastName='Last Name';
con.AccountId=obj.id; // Mapping contact torespective
Account.
conList.add(con); // Adding all contact in List. We
should always perform DML operations on the collection of records to avoid hitting
governor limit.
}
if(conList.size() > 0){ // Checking if the list has
records.
insert conList; // Inserting contact list.This is
how we should perform DML operations on the collection of records.
}
}
}
will trigger.new works for after triggers??
ReplyDeletei dont think it works. because there is no trigger.new records as the record is already ineterted. trigger.new works only before triggers.Please correct the code.
DeletePlease refer https://www.sfdc-lightning.com/2019/10/availability-of-trigger.new-trigger.old-in-apex-trigger.html
DeleteYes it will work, please try in org.
DeleteThis is basically used to create child records after parent record is inserted.
DeleteGood Information
ReplyDelete