• shiva reddy 59
  • NEWBIE
  • 0 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies
trigger CreationOfContact on Account (after insert,after Update) {
Map<Id,Decimal> mp=new Map<Id,Decimal>();
list<Contact> lst=new List<Contact>();
  for(Account a:Trigger.New)
  { 
   mp.put(a.id,a.Number_Of_Contacts__c);
  }
   if(Trigger.isInsert && Trigger.isAfter)
   {
    if(mp.size()>0 && mp!=null)
    {
     for(Id a:mp.keyset())
     {
      for(Integer i=1;i<=mp.get(a);i++)
      {
        Contact c=new Contact();
        c.lastname='Test'+i;
        c.accountid=a;
        lst.add(c);
      }
     }
    }
   }
   insert lst;
   if(Trigger.isUpdate && Trigger.isAfter)
   {
    
   for(Account a:Trigger.new)
   {
    Decimal a1=trigger.oldmap.get(a.id).Number_Of_Contacts__c;
    Decimal a2=trigger.newMap.get(a.id).Number_Of_Contacts__c;
    Decimal a3=0;
    if(a2>a1)
    {
      a3=a2-a1;
      for(Integer i=1;i<=a3;i++)
      {
        Contact c=new Contact();
        c.lastname='Update' +i;
        c.AccountId=a.id;
        lst.add(c);
      }
     }    
    }
      insert lst;
   }
   
}


In this trigger i have created a custom field called no.of.contacts on account object, i've the following scenario:
1. When a new account is created and the that field is populated with (say 2) it should create 2 new contacts.

2. When i edit the that field ( say to 5 now before it was 2 ) so the difference of both is now 3, so it should 3 more contacts.

3. when i edit that field to (say to 4 now earlier the new updated value is 5) so the difference is 1 here , therefore 1contact should be deleted.


So, the code i've written works well upto 2nd scenario, the only problem i;m facing now is at 3rd scenario.

Could someone help me out?