Salesforce Apex Trigger can be used to set the latest Opportunity for an Account.
In the following Apex Trigger, I have used a custom field “Latest_Opportunity__c” on the Opportunity Object. This new custom field “Latest_Opportunity__c” on the Opportunity Object will be set as true for only one latest Opportunity for a given account record. Opportunities are ordered by the Created Date to find the latest. For the out-of-date opportunities, it will be set as false.
Sample Apex Trigger:
trigger OpportunityTrigger on Opportunity ( before insert, after insert ) {
/*
* For every new Opportunity, we can set the Latest as true
*/
if ( trigger.isBefore && trigger.isInsert ) {
for ( Opportunity objOppty : trigger.new ) {
if ( String.isNotBlank( objOppty.AccountId ) ) {
objOppty.Latest_Opportunity__c = true;
}
}
}
/*
* After the Opportunity creation,
* we can set the Latest as false for the existing ones
*/
if ( trigger.isAfter && trigger.isInsert ) {
Set < Id > setAccountIds = new Set < Id >();
for ( Opportunity objOppty : trigger.new ) {
if ( String.isNotBlank( objOppty.AccountId ) ) {
setAccountIds.add( objOppty.AccountId );
}
}
if ( setAccountIds.size() > 0 ) {
List < Opportunity > listOpportunities = new List < Opportunity >();
for ( Account objAccount : [
SELECT Id, (
SELECT Id, Latest_Opportunity__c
FROM Opportunities
WHERE Latest_Opportunity__c = true
ORDER BY CreatedDate DESC
)
FROM Account
WHERE Id IN: setAccountIds
] ) {
Boolean isLatestOppty = true;
for ( Opportunity objOppty : objAccount.Opportunities ) {
if ( isLatestOppty ) {
isLatestOppty = false;
} else {
objOppty.Latest_Opportunity__c = false;
listOpportunities.add( objOppty );
}
}
}
if ( listOpportunities.size() > 0 ) {
update listOpportunities;
}
}
}
}
Sample Apex Code to check the trigger:
You can execute the following apex code to check the functionality.
//Creating Account record
Account objAccount = new Account( Name = 'Test1af' );
insert objAccount;
//Creating Opportunity records
List < Opportunity > listOpptys = new List < Opportunity >();
Opportunity oppty1 = new Opportunity();
oppty1.Name = 'Test 1';
oppty1.AccountId = objAccount.Id;
oppty1.StageName = 'Qualification';
oppty1.CloseDate = Date.today().addDays( 30 );
listOpptys.add( oppty1 );
Opportunity oppty2 = new Opportunity();
oppty2.Name = 'Test 2';
oppty2.AccountId = objAccount.Id;
oppty2.StageName = 'Qualification';
oppty2.CloseDate = Date.today().addDays( 30 );
listOpptys.add( oppty2 );
insert listOpptys;