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
Raj Pandey 29Raj Pandey 29 

write a trigger for creating only one opportunity linked with an account in a single day

trigger onlyoneaccountopportunitycreate on Opportunity (before insert) {

    Set<id> accId = new Set<id>(); // Always try to use set
    for(opportunity opp : trigger.new)
    {
        if(opp.AccountId != null)
        {
            accId.add(opp.AccountId);    
        }
        }
    

    Map<Id,Account> mapAccount = new Map<Id,Account> ( [select id,(select id from opportunities) from account where id IN : accId ]) ;
    for(opportunity opp:trigger.new)
    {    
        
        if( opp.AccountId != null && mapAccount.containsKey(opp.AccountId) )
        {
            Account acc = mapAccount.get(opp.AccountId);
            if(acc.opportunities.size() > 0 )
            {
                opp.addError('you can not add more then once opportunity for this account'); 
            }
        }
    }

}

Please see the above code & help me to write a trigger that allow only one opportunity associated with an account in a day.
Best Answer chosen by Raj Pandey 29
Abhishek BansalAbhishek Bansal
Please close this question by marking the answer as Best Answer so that it will be helpful to others 

All Answers

Abhishek BansalAbhishek Bansal
Hi Raj,

Just add the created date filter in the opportunity inner query so that it will check if the opportunity is created today only. Please find the updaed code below:
trigger onlyoneaccountopportunitycreate on Opportunity (before insert) {

    Set<id> accId = new Set<id>(); // Always try to use set
    for(opportunity opp : trigger.new)
    {
        if(opp.AccountId != null)
        {
            accId.add(opp.AccountId);    
        }
        }
    

    Map<Id,Account> mapAccount = new Map<Id,Account> ( [select id,(select id from opportunities where CreatedDate = TODAY) from account where id IN : accId ]) ;
    for(opportunity opp:trigger.new)
    {    
        
        if( opp.AccountId != null && mapAccount.containsKey(opp.AccountId) )
        {
            Account acc = mapAccount.get(opp.AccountId);
            if(acc.opportunities.size() > 0 )
            {
                opp.addError('you can not add more then once opportunity for this account'); 
            }
        }
    }

}

Let me know if you need any further help on this.

Thanks,
Abhishek Bansal.​​​​​​​
Raj Pandey 29Raj Pandey 29
Thanks ,
sir
Abhishek BansalAbhishek Bansal
Please close this question by marking the answer as Best Answer so that it will be helpful to others 
This was selected as the best answer
Raj Pandey 29Raj Pandey 29
Hi Abhishek Sir If want to follow you then how it can i follow you 
 
Raj Pandey 29Raj Pandey 29
I want you in my contact