function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
NK ShaNK Sha 

trigger to calculate how many male and female contact’s are on an account. Gender is an picklist Value field

trigger to calculate how many male and female contact’s are on an account.    Gender is an picklist Value field
Khan AnasKhan Anas (Salesforce Developers) 
Hi,

Greetings to you!

Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.
 
trigger CountGender on Contact (after insert,after update,after delete) {
    
    List<Contact> con = Trigger.isdelete ? trigger.old : trigger.new;
    Set<Id> accountIds = new Set<Id>();
    
    for (Contact c : con) {
        if (c.accountid != null) {
            accountIds.add(c.accountid);
        } 
    }
    
    List<account> femaleGenderList = [SELECT Count_Of_Female_Gender__c,(SELECT Id FROM Contacts WHERE Gender__c='Female') FROM Account WHERE Id IN :accountIds];    
    for(account a :femaleGenderList)  {
        a.Count_Of_Female_Gender__c = a.contacts.size();
    }
    
    List<account> maleGenderList = [SELECT Count_Of_Male_Gender__c,(SELECT Id FROM Contacts WHERE Gender__c='Male') FROM Account WHERE Id IN :accountIds];    
    for(account a :maleGenderList)  {
        a.Count_Of_Male_Gender__c = a.contacts.size();
    }
    
    if(femaleGenderList.size()>0){
    	UPDATE femaleGenderList ;
    }
    if(maleGenderList.size()>0){
    	UPDATE maleGenderList ;
    }
}

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
NK ShaNK Sha
Hello Dear khan

There is an No such fileds : Count_Of_Female_Gender__c   On the Account object  ( I wanted to be take an Account Id

Account  and  for the account related Contacts : 
Ex:- for One account there is an 3 contacts
the Contactes Gender information (count of how many Male or Female )
I don't wanted to be create any Additional fields