How to declaratively prevent two Opportunities being created on a single Account on the same day in Salesforce?

How to declaratively prevent two Opportunities being created on a single Account on the same day in Salesforce?

1. Create a custom field on the Account.

2. Create a Workflow Rule on the Opportunity Object.

3. Create a Field Update on Opportunity Object.

4. Create a Validation Rule on the Opportunity Object.

Output:

For doing the same development using Apex Trigger, check the below

Sample Trigger:

trigger OpportunityTrigger on Opportunity ( before insert ) {
    
    Set < Id > setAccountIds = new Set < Id >();
    Map < Id, List < Opportunity > > mapAccIdNewOpptyList = new Map < Id, List < Opportunity > >();
    Map < Id, List < Opportunity > > mapAccIdOldOpptyList = new Map < Id, List < Opportunity > >();
    
    for ( Opportunity objOppty : trigger.new ) {
    
        if ( String.isNotBlank( objOppty.AccountId ) ) {
        
            setAccountIds.add( objOppty.AccountId );
            
            if ( !mapAccIdNewOpptyList.containsKey( objOppty.AccountId ) )
                mapAccIdNewOpptyList.put( objOppty.AccountId, new List < Opportunity > () );
                
            mapAccIdNewOpptyList.get( objOppty.AccountId ).add( objOppty );
            
        }
    
    }
    
    if ( setAccountIds.size() > 0 ) {
        
        for ( Opportunity objOppty : [ SELECT Id, AccountId FROM Opportunity WHERE AccountId IN: setAccountIds AND CreatedDate = TODAY ] ) {
        
            if ( !mapAccIdOldOpptyList.containsKey( objOppty.AccountId ) )
                mapAccIdOldOpptyList.put( objOppty.AccountId, new List < Opportunity > () );
                
            mapAccIdOldOpptyList.get( objOppty.AccountId ).add( objOppty );
        
        }       
        
        for ( Opportunity objOppty : trigger.new ) {
        
            if ( String.isNotBlank( objOppty.AccountId ) ) {
            
                if ( mapAccIdOldOpptyList.containsKey( objOppty.AccountId ) )
                    objOppty.addError( 'Opportunity already added for this Account today' );
                else if ( mapAccIdNewOpptyList.containsKey( objOppty.AccountId ) && mapAccIdNewOpptyList.get( objOppty.AccountId ).size() > 1 )
                    objOppty.addError( 'You cannot import multiple opportunities to the same account at the same day' );
            
            }
        
        }
        
    }

}

To check multiple opportunities getting inserted at the same time for an account, use the below code and execute in Anonymous Window.

List < Opportunity > listOppty = new List < Opportunity >();
listOppty.add( new Opportunity( Name = 'Testing 1', StageName = 'Qualification', CloseDate = System.today(), AccountId = '0014x00000FE6CEAA1' ) );
listOppty.add( new Opportunity( Name = 'Testing 2', StageName = 'Qualification', CloseDate = System.today(), AccountId = '0014x00000FE6CEAA1' ) );
insert listOppty;

Leave a Reply