First note that, trigger is invoked when some insert/update/delete command is run for some object. Steps to insert record using trigger.
1. Create a trigger on some object. trigger testTrigger on Account (after insert) { //For now, we will define it after insert of account if(Trigger.isAfter and Trigger.isInsert){ List<Account> accList = new List<Account>(); for(Account tempAcc : Trigger.New){ accList.add(tempAcc.Id); } //Use helper class ContactClass.insertRecord(accList); } }
2. Create a helper class public class ContactClass{ public ContactClass(){ }
Thanks!
Steps to insert record using trigger.
1. Create a trigger on some object.
trigger testTrigger on Account (after insert) { //For now, we will define it after insert of account
if(Trigger.isAfter and Trigger.isInsert){
List<Account> accList = new List<Account>();
for(Account tempAcc : Trigger.New){
accList.add(tempAcc.Id);
}
//Use helper class
ContactClass.insertRecord(accList);
}
}
2. Create a helper class
public class ContactClass{
public ContactClass(){
}
public void insertRecord(List<Account> lstAccount){
List<Contact> contactList = new List<Contact>();
if(lstAccount.size() > 0){
for(Account acc : lstAccount){
Contact c = new Contact();
c.lastname = 'Contact ' + acc.Name;
c.accountid = acc.id;
contactList.add(c);
}
}
if(contactList.size() > 0 ){
insert contactList;
}
}
}
Mark as best answer, if it works.!
Thank and Regards,
Akanksha