1

I have a custom object Customer with a few fields. One of the fields is a Lookup field that refers to a standard object Account. I'm writing a trigger that should fire before each insert/update.

The question is: how do I access that Account record via that custom class?

Some of the code that I use:

List<Customer__c> customerList = [SELECT Id, Title__c, First_name__c, Last_name__c, Address__c, Gender__c, Age__c, RefAccount__c, RefAccount__r.Priority__c FROM Customer__c];
for (Customer__c cust : customerList) {
    customerMap.put(cust.Title__c + ' ' + cust.First_name__c + ' ' + cust.Last_name__c, cust.Id);
}

for (Customer__c cust : customers) {
    String key = cust.Title__c + ' ' + cust.First_name__c + ' ' + cust.Last_name__c;
    if (customerMap.containsKey(key) && customerMap.get(key) != cust.Id) {            
        List<Customer__c> c1 = new List<Customer__c>();
        for (Customer__c c : customerList) {
            if (key.equals(c.Title__c + ' ' + c.First_name__c + ' ' + c.Last_name__c) && c != cust) {
                c1.add(c);
            }
        }
...
...
...
        Integer custP, c1P;
        try {
            c1P = Integer.valueOf(c1[0].RefAccount__r.Priority__c);
            custP = Integer.valueOf(cust.RefAccount__r.Priority__c);
        } catch (Exception e) {
        }
        if (c1P != null) {
            if (custP == null) {
                cust.RefAccount__c = c1[0].RefAccount__c;
            }
            if (custP < c1P) {
                cust.RefAccount__c = c1[0].RefAccount__c;
            }
        }
    }
}

I heard that RefAccount__r doesn't work in triggers and I should use queries, but I have no idea how to get to that RefAccount record.

9

You have to go and query the Account records within the trigger (or the class it delegates to), and to avoid governor limit problems they should be queried all at once:

trigger MyTrigger on Customer__c (before insert, before update) {
    Set<Id> accountIds = new Set<Id>();
    for (Customer__c : Trigger.new) {
        if (c.RefAccount__c != null) {
            accountIds.add(c.RefAccount__c);
        }
    }
    // Handy special map constructor
    Map<Id, Account> accounts = new Map<Id, Account>([
            select Id, Priority__c
            from Account
            where Id in :accountIds
            ]);
    for (Customer__c : Trigger.new) {
        if (c.RefAccount__c != null) {
            Account a = accounts.get(c.RefAccount__c);
            // Use a with c
        }
    }
}

(Or you can repeat the query with the referenced objects in the query as you show in the first line of your code, but as the trigger context already includes all the field values arguably that is wasteful.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.