+ Start a Discussion
mahi rafimahi rafi 

how to insert new record using trigger

SaravaSarava
Below is a sample code which trigger to create a contact after an account insert. You can try something like this based on your functionality.
trigger test_trigger on Account (after insert) {
    List<contact> conlst = new List<contact>();
    for(account acc : trigger.new){
    if(acc.Primary_Contact__c == null){
        Contact con = new contact();
        con.lastname = 'test name';
        con.accountid = acc.id;
        conlst.add(con);
    }
    } 
    if (conlst.size()>0){
    insert conlst;
    }
}

Thanks!
Akanksha JadhavAkanksha Jadhav
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(){
    }
  
    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