+ Start a Discussion
Eric BlaxtonEric Blaxton 

Apex Cross Object Trigger help...

Hi and thanks in advance...

Requirement: Before inserting New Opportunity check Account.Credit_Status__C (custom field).  If it doesn't meet requirements pop-up message.  If this is not the way it's done feel free to offer ideas.

Here is the code
trigger checkAccountCreditStatusisRejected on Opportunity (before insert) {
      
     for (Opportunity opp : System.trigger.new) {           
        if (opp.AccountId.Credit_Status__c == 'Rejected')
          {
             opp.addError('A new Opportunity cannot be created on account where Credit Status = Rejected');
          }// end if         
                        
       }//end for   
     
}// end trigger

Regards
Best Answer chosen by Eric Blaxton
Ankit Gupta@ DeveloperAnkit Gupta@ Developer

Hi,

Try the below modified code

trigger checkAccountCreditStatusisRejected on Opportunity (before insert) {
     
   list<id>AccountidLst=new list<id>();
  
   for(Opportunity opp : System.trigger.new)
  {
   AccountidLst.add(opp.AccountId);
  }

  map<id,account>accountMap=new map<id,account>([select id,Credit_Status__c from account where id In : AccountidLst]);
     for (Opportunity opp : System.trigger.new) {          
   if(accountMap.containskey(opp.AccountId))
   {
    if (accountMap.get(opp.AccountId).Credit_Status__c == 'Rejected')
    {
     opp.addError('A new Opportunity cannot be created on account where Credit Status = Rejected');
    }// end if 
   }

                       
       }//end for  
    
}// end trigger

 

Thanks
Ankit Gupta

All Answers

Ankit Gupta@ DeveloperAnkit Gupta@ Developer

Hi,

Try the below modified code

trigger checkAccountCreditStatusisRejected on Opportunity (before insert) {
     
   list<id>AccountidLst=new list<id>();
  
   for(Opportunity opp : System.trigger.new)
  {
   AccountidLst.add(opp.AccountId);
  }

  map<id,account>accountMap=new map<id,account>([select id,Credit_Status__c from account where id In : AccountidLst]);
     for (Opportunity opp : System.trigger.new) {          
   if(accountMap.containskey(opp.AccountId))
   {
    if (accountMap.get(opp.AccountId).Credit_Status__c == 'Rejected')
    {
     opp.addError('A new Opportunity cannot be created on account where Credit Status = Rejected');
    }// end if 
   }

                       
       }//end for  
    
}// end trigger

 

Thanks
Ankit Gupta

This was selected as the best answer
Eric BlaxtonEric Blaxton
Ankit, Thank you for your help. Can you provide some tips on developing a test for this trigger? Regards, Eric
Ankit Gupta@ DeveloperAnkit Gupta@ Developer
Hi,

in test class you need to fulfill all the positive and negative condition of your code.

Refer the below link for more detail
http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_qs_test.htm

Ankit Gupta