0

I'm writing an Apex trigger that needs to fire if the opportunity record has one of two values selected on the Forecast Category picklist fields AND a field on the related account is null. How do I represent the following

IF( criteria one AND (criteria two OR criteria three)?

Previously the trigger only needed to be one value from the forecast category picklist and the account field being null, and my trigger worked perfectly. Now it isn't working as intended. Code is below.

for(opportunity o : trigger.new){
                if((o.ForecastCategoryName == 'Commit'||
                    o.ForecastCategoryName == 'Won') && 
                   o.account.paycom_account_number__c == null){

1 Answer 1

0

Your previous code couldn't have worked, parent objects are not automatically loaded in a trigger (e.g. see this). You need to query the accounts before you can use them.

Map<Id, account> accountMap = new Map<id, Account>();
for(Opportunity o: Trigger.new) {
  accountMap.put(o.AccountId, new Account());
}
accountMap.putAll([SELECT paycom_account_number__c FROM Account WHERE Id = :accountMap.keySet()]);
for(opportunity o : trigger.new){
    if((o.ForecastCategoryName == 'Commit'||
        o.ForecastCategoryName == 'Won') && 
        accountMap.get(o.accountid).paycom_account_number__c == null){
3
  • And once I make that change, the if logic will work as stated?
    – sfAndTri
    Jul 29, 2020 at 16:32
  • @sfAndTri Yes, that should fix your problem.
    – sfdcfox
    Jul 29, 2020 at 16:34
  • Thank you for the help with querying the accounts first and mapping them. I was still having errors with the logic of the if statement, so I first ran an if looking at the opportunity fields, and if that evaluated to true, triggered a query on the account object, and did an if statement on the account field (paycom account number). Thank you very much!
    – sfAndTri
    Jul 29, 2020 at 18:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .