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
Rajesh Singh 88Rajesh Singh 88 

Trigger to Auto Increment the field to the required Financial Quarter

In my company the Financial Year starts from April - March. My requirement is When the Period__c ( picklist ) is updated to Quarter 1 then the Financial_Period__c is updated to FY21 - Q1.

The Financial_Period__c needs to be incremented based up on the Financial Year.

I am new to Apex , can someone please help me in this.

Period__c picklist values : 
Quarter 1
Quarter 2
Quarter 3
Quarter 4

Example  for FY21:

If the Period__c is updated to Quarter 2 the Financial_Period__c is updated to FY21 - Q2

If the Period__c is updated to Quarter 4 the Financial_Period__c is updated to FY21 - Q4

Similarly for FY22 :

If the Period__c is updated to Quarter 2 the Financial_Period__c is updated to FY22 - Q2

Similarly for FY24 :

If the Period__c is updated to Quarter 2 the Financial_Period__c is updated to FY24 - Q2

Thanks!
 
Best Answer chosen by Rajesh Singh 88
Suraj Tripathi 47Suraj Tripathi 47
Hi Rajesh Singh 88,
Answer:
You have not mentioned on which Sobject these two fields(Period__c and Financial_Period__c) are present. I assumed these two fields are on the Opportunity object. I have written trigger for your mentioned requirement

Trigger:
trigger OpportunityTrigger on Opportunity (before update, before insert) {
    if(trigger.isBefore && trigger.isUpdate){
       OpportunityTriggerHandlers.updateFinancialYear(trigger.new);
       
    }
	if(trigger.isBefore && trigger.isInsert){
       OpportunityTriggerHandlers.updateFinancialYear(trigger.new);
       
    }
}
Trigger Handler:
public class OpportunityTriggerHandlers {
    public static void updateFinancialYear(List<Opportunity> oppNewList){
        try{
            
			String currentYear = System.today().year().format().substring(3);     // this will get our current year.

                for(Opportunity oppObj : oppNewList ){
					if(oppObj.Period__c != NULL){
						if(oppObj.Period__c == 'Quarter 1'){
							oppObj.Financial_Period__c  = 'FY'+currentYear+' - Q1';
						}
						else if (oppObj.Period__c == 'Quarter 2'){
							oppObj.Financial_Period__c  = 'FY'+currentYear+' - Q2';
						}
						else if (oppObj.Period__c == 'Quarter 3'){
							oppObj.Financial_Period__c  = 'FY'+currentYear+' - Q3';
						}
						else{
							oppObj.Financial_Period__c  = 'FY'+currentYear+' - Q4';

						}
					}
                   
                }
            
        }
        catch(Exception e){
            System.debug('Error message>>> '+e.getMessage() +'at line >>'+e.getLineNumber());
        }
    }
    
    
}



I hope you find the above solution helpful. If it does, please mark it as Best Answer to help others too.

Thanks and Regards,
Suraj Tripathi