• saurabh singh 310
  • NEWBIE
  • 5 Points
  • Member since 2023

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 4
    Replies
Trigger:-

trigger AccountContactTrig on Account (after insert,after update) {
     Set<Id> accIds= new Set<Id>();
    If(Trigger.isinsert && Trigger.isafter){
        List<Contact> cont = new List <Contact>();
        for(Account acc : trigger.new){
            Contact c = new Contact();
            c.AccountId=acc.id;
            c.LastName = acc.name;
            cont.add(c);
        }
        insert cont; 
    }
    if(Trigger.isupdate && Trigger.isafter){
        Set<String> accnames= new Set<String>();
        For(Account acc:Trigger.new){
            Account oldacc= Trigger.oldmap.get(acc.id);
            if(acc.name!= oldacc.Name){
                accnames.add(acc.name);
            }
        }
        Map<Id,Account> mapaccounts = new Map<Id,Account>([Select Name,(Select id, Lastname from contacts where Lastname in: accnames) from Account where id in:Trigger.new]);
        List<Contact> cont = new List <Contact>();
        if(mapaccounts.size()>0){
        for(Account ac: Trigger.new){
            if(Ac.Name != trigger.OldMap.get(Ac.Id).Name){               
            if(mapaccounts.containsKey(ac.id)){
                if(mapaccounts.get(ac.id).Contacts.size()==0){
                        Contact c = new Contact();
                        c.AccountId=ac.id;
                        c.LastName = ac.name;
                        cont.add(c);
                }
            }
        }
         insert cont;
    }
        }
    }
}
Write an apex program, to insert an Account Record, and 5 Related Contacts, and 4 Related Opportunities, and 2 Related Case records inside the object.
Account record(1)
|
|_______contact records(5)
|
|_______Opportunity records(4)
|
|________Case records(2)