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
Adam LeeAdam Lee 

Validation Apex Trigger help

Hi all,

I am creating a trigger to prevent users entering the same "Business_Planning__c" record for the same Month ("Broker_BPMonth__c" field).

How do I refer this trigger to only look at the current Account and not all accounts on SF?
 
trigger ForecastPreventDup on Business_Planning__c (before insert, before update) {
    
    Map<String, Business_Planning__c> monthMap = new Map <String, Business_Planning__c>();
    //Map<Id, Business_Planning__c> accMap = new Map <Id, Business_Planning__c>();
    for (Business_Planning__c b:System.Trigger.new){
        if((b.Broker_BPMonth__c!=null)&&
            (System.Trigger.isInsert ||
            ((b.Broker_BPMonth__c!=
             System.Trigger.oldMap.get(b.Id).Broker_BPMonth__c )
             && b.Account__c == System.Trigger.oldMap.get(b.Id).Account__c))){
                 
                 if(monthMap.containsKey(b.Broker_BPMonth__c)){
                     b.Broker_BPMonth__c.addError('Forecast for this month already exists');
                 }else{
                     monthMap.put(b.Broker_BPMonth__c, b);
                 }
             }
    }
    
    for(Business_Planning__c b:[Select Broker_BPMonth__c From Business_Planning__c 
                                WHERE Broker_BPMonth__c IN :monthMap.keySet()]){
                                    Business_Planning__c newBP = monthMap.get(b.Broker_BPMonth__c);
                                    newBP.Broker_BPMonth__c.addError('Forecast for this month already exists');
                                }
    
    

}


Thanks

Adam
Best Answer chosen by Adam Lee
Adam LeeAdam Lee
SOLVED

All Answers

EnreecoEnreeco
Hi Adam,
What you mean for "current Account"?
Adam LeeAdam Lee
The Account this record linked to
Adam LeeAdam Lee
SOLVED
This was selected as the best answer