+ Start a Discussion
Russell baker 1Russell baker 1 

Want to add all opportunities in pipeline and closed won into Custom Object(Budget) realted list according to closed date.

I  created a custom object budget which will store company budget for every month. I created opportunity related list into budget and I want to show all opportunities into that related list according to close date. Let say if any opportunity close date is Jan so it should be show under Jan budget. How can I achieve this do I need to create trigger to pull all opportunities into budget related list.

User-added image
suresh sanneboina 4suresh sanneboina 4
Hello,

You need to create a Batch Class and needs to execute the batch class at the end of every month.

Please find the below code.

Batch Class:
//Batch Class
global class UpdateOpportunities implements Database.Batchable<sObject>
{
	global datetime startdatetime;
	global datetime enddatetime;
	public integer year=system.today().year();
	public integer month=system.today().month();
	public integer day=system.today().day();
	
	public UpdateOpportunities(){
		startdatetime=datetime.newInstance(year, month, 1, 0, 0, 0);
		enddatetime=system.now();           
	}
	
	global Database.QueryLocator start(Database.BatchableContext BC) 
	{
		String query = 'SELECT Id FROM Opportunity where createddate>=:startdatetime and createddate<=:enddatetime';
		return Database.getQueryLocator(query);
	} 
	
	global void execute(Database.BatchableContext BC, List<sobject> scope)
	{
		List<Opportunity> listtoprocess=new List<Opportunity>();
		String monthName;
		if(system.today().month() ==1){
		monthName ='January';
		}else if(system.today().month() ==2){
		monthName ='Feburary';
		}else if(system.today().month() ==3){
		monthName ='March';
		}else if(system.today().month() ==4){
		monthName ='April';
		}else if(system.today().month() ==5){
		monthName ='May';
		}else if(system.today().month() ==6){
		monthName ='June';
		}else if(system.today().month() ==7){
		monthName ='July';
		}else if(system.today().month() ==8){
		monthName ='August';
		}else if(system.today().month() ==9){
		monthName ='September';
		}else if(system.today().month() ==10){
		monthName ='October';
		}else if(system.today().month() ==11){
		monthName ='November';
		}else if(system.today().month() ==12){
		monthName ='December';
		}

		Budget__c bstation=[Select Id,Name From Budget__c Where Name = : monthName limit 1];
		if(bstation != null)
		{
			for(sobject b:scope)
			{
				Opportunity c=(Opportunity)b;
				c.Budget__c = bstation.Id;
				listtoprocess.add(c);
			}
		}

		if(!listtoprocess.isEmpty())             
		{
			update listtoprocess;
		}
	}  
	
	global void finish(Database.BatchableContext BC)
	{
	}
}
Schedule class
//Schedulable Class
global class UpdateOpps_schedule implements Schedulable {

	global void execute(SchedulableContext c)
	{
		Database.executeBatch(new UpdateOpportunities());
	}
}