Hi Pawan,
The trigger provided below will work for newly created account and contact’s records, set the default value 0 for the two number fields created on account. This trigger will work for insert/update/delete on contact.
trigger Count_MalesAndFemales on Contact (after insert, after update, before delete)
{
//System.debug(‘ggg’+Trigger.Old[0].AccountId);
List<Account> accList = new List<Account>();
Map<Id,Contact> mapIdVsCon = new Map<Id,Contact>();
if(Trigger.isAfter&&Trigger.isInsert)
{
List <Contact> conListNew = [SELECT Gender__c, AccountId, Account.news__No_Of_Males__c, Account.news__No_Of_Females__c FROM Contact WHERE AccountId !=Null And Id IN : Trigger.new ];
for(Contact con : conListNew)
{
if(con.Gender__c == ‘Male’)
{
con.Account.No_Of_Males__c++;
System.debug(‘sss’+con.Account.No_Of_Males__c);
}
else if(con.Gender__c == ‘Female’)
{
con.Account.No_Of_Females__c++;
System.debug(‘hhh’+con.Account.No_Of_Females__c);
}
mapIdVsCon.put(con.AccountId,con);
//accList.add(acc);
}
}
if(Trigger.isAfter&&Trigger.isUpdate)
{
List <Contact> conListNew = [SELECT Gender__c, AccountId, Account.news__No_Of_Males__c, Account.news__No_Of_Females__c FROM Contact WHERE AccountId !=Null And Id IN : Trigger.new ];
for(Contact con : conListNew)
{
if(Trigger.newMap.get(con.Id).Gender__c == ‘Male’ && Trigger.oldMap.get(con.Id).Gender__c == ‘Female’)
{
con.Account.No_Of_Females__c–;
con.Account.No_Of_Males__c++;
}
else if(Trigger.oldMap.get(con.Id).Gender__c == ‘Male’ && Trigger.newMap.get(con.Id).Gender__c == ‘Female’)
{
con.Account.No_Of_Females__c++;
con.Account.No_Of_Males__c–;
}
mapIdVsCon.put(con.AccountId,con);
//accList.add(acc);
}
}
if(Trigger.isBefore&&Trigger.isDelete)
{
List <Contact> conListOld = [SELECT Gender__c, AccountId, Account.news__No_Of_Males__c, Account.news__No_Of_Females__c FROM Contact WHERE AccountId !=Null And Id IN : Trigger.old ];
for(Contact con : conListOld)
{
System.debug(‘sss’+con);
System.debug(‘sss’+Trigger.oldMap.get(con.Id));
if(con.Gender__c == ‘Female’)
{
System.debug(‘sss’+Trigger.oldMap.get(con.Id));
con.Account.No_Of_Females__c–;
}
else if(con.Gender__c == ‘Male’ )
{
System.debug(‘sss’+Trigger.oldMap.get(con.Id));
con.Account.No_Of_Males__c–;
}
mapIdVsCon.put(con.AccountId,con);
//accList.add(acc);
}
}
for(Id ide : mapIdVsCon.keySet())
{
Account a = new Account();
a.Id = ide;
a.news__No_Of_Males__c = mapIdVsCon.get(ide).Account.news__No_Of_Males__c;
a.news__No_Of_Females__c = mapIdVsCon.get(ide).Account.news__No_Of_Females__c;
accList.add(a);
System.debug(‘key====’+ide);
System.debug(‘id=====’+mapIdVsCon.get(ide));
}
update accList;
}