• Trigger Scenario: Whenever New Account Record is created then needs to create associated Contact Record automatically

    Published By: Venu Gutta
    Published on: Saturday, 18 March 2017
    A- A+

    Object : Account
    Trigger: After Insert

    Description : When ever new Account record is successfully created  then
         create the corresponding  contact record for the account 
    with 
    account name as contact lastname 
    account phone as contact phone

    Trigger Code:

    trigger accountAfter on Account (after insert) {
        List<Contact> cons=new List<Contact>();
        for(Account a: Trigger.New){
            Contact c=new Contact();
            c.accountid=a.id;
            c.lastname=a.name;
            c.phone=a.phone;
            cons.add(c);
        }
        insert cons;

    }


    Test Class  :

    @isTest
    private class AccountAfter {
    @isTest
        static void testme(){
            Integer count=[select count() from Account];
            Integer size=[select count() from Contact];
            Account a=new Account(Name='Testing',phone='111');
            try{
                insert a;
            }catch(Exception e){
                System.debug(e);
            }
            Integer newCount=[select count() from Account];
            Integer newsize=[select count() from Contact];
            Contact c=[select lastname,phone from Contact where accountid=:a.id];
            System.assertEquals(c.lastname,a.name);
            System.assertEquals(c.phone,a.phone);
        }
    }
  • 1 comment to ''Trigger Scenario: Whenever New Account Record is created then needs to create associated Contact Record automatically"

    ADD COMMENT
    1. trigger CreateContactOnAccount on Account (after insert) {
      list con = new list();
      for(account a:trigger.new)
      {
      contact c=new contact();
      c.firstname='jitu';
      c.lastname='negi';
      c.AccountId=a.id;
      con.add(c);
      }
      insert con;
      }

      ==========================================
      TestClass:-
      -----------

      @istest
      public class CreateContactOnAccountTest {

      public static testmethod void CreateconTest()
      {

      Account a = new Account();
      a.Name='james';
      insert a;
      contact c = [select lastname from contact where accountid =:a.Id];
      system.assertEquals('Negi',c.lastname );


      }

      }

      ReplyDelete