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
jayesh pagarejayesh pagare 

Trigger to get child record count based createddate for current months/previous months?

I have related contacts and on account i want to get record count of contacts created this month and record count of contacts created on last month
Siddharth ManiSiddharth Mani
Assuming you have fields created on Account for both requirements, for current month - the below code should work:
 
trigger updateNoOfContacts on Account (before insert, before update) {
	List<Contact> conList = new List<Contact>();
    List<Account> accList = new List<Account>();
    List<Contact> conThisMonth = new List<Contact>();
    Integer currentMonth = date.today().month();
    for(Account acc : Trigger.new) {
        accList.add(acc);
    }
    
    conList = [SELECT Id,CreatedDate, Name FROM Contact WHERE AccountId IN : accList];
    for (Contact con : conList) {
        if(con.CreatedDate.month() == currentMonth) {
            conThisMonth.add(con);
        }
    }
    for(Account accn : Trigger.new) {
    	accn.Contacts_Created_This_Month__c = conThisMonth.size();    
    }
    
}

You have to figure out how to do it for the previous month! Try to get the previous month (number) and use the same logic as above - Simple way is to subtract 1 from currentMonth and follow the same logic - but this may not work for January :)
jayesh pagarejayesh pagare
Thanks a lot!
mritzimritzi
Create new Trigger on Contact
(Reason: An account can have multiple contacts and contacts are usually created after account creation, so in standard scenarios contact count would be zero on Account creation and hence a Trigger on Account won't serve the purpose)

Paste the following code there (change filed name of number fileds on Account object in code)
Let me know how it works
 
trigger UpdateAccountData on Contact(after Insert, after Update){
	
	//to store ids of Accounts
	List<Id> acIds = new List<Id>();
	for(Contact c : Trigger.new){
		if(c.AccountId!=null)
			acIds.add(c.AccountId);
	}
	Date today = date.today();
	Date prevMonDate;
	if(today.month()==1){
		prevMonDate = date.newinstance(today.year()-1,12,01);
	}
	else
		prevMonDate = date.newinstance(today.year(),today.month()-1,01);
	//update actual feild names in following query
	List<Account> acList = [Select id,current_months_contacts__c,previous_months_contatcs__c From Account Where Id IN :acIds];
	// stores count of contacts for each AccountId having created Date in current month
	List<AggregateResult> arCurMonth = [Select COUNT(id),AccountId From Contact Where AccountId!=null AND CALENDAR_MONTH(CreatedDate)=:today.month() GROUP BY AccountId];
    // stores count of contacts for each AccountId having created Date in previous month
	List<AggregateResult> arPrevMonth = [Select COUNT(id),AccountId From Contact Where AccountId!=null AND CALENDAR_MONTH(CreatedDate)=:prevMonDate.month() GROUP BY AccountId];
	
	for(Account a : acList){
		for(AggregateResult ar : arCurMonth){
			if(a.id == ar.get('AccountId')){
				//update actual feild name below
				a.current_months_contacts__c = ar.get('expr0');
				break;
			}
		}
		forAggregateResult ar : arPrevMonth){
			if(a.id == ar.get('AccountId')){
				//update actual feild name below
				//expr0 holds count data -> COUNT(Id)
				a.previous_months_contacts__c = ar.get('expr0');
				break;
			}
		}
	}
	update acList;
}


Hit LIKE it it helps you. Mark it as Best Answer if it solves your problem.