0

I am writting a trigger on Lead object. Where I want to fetch the contact Id and by using that contact Id I will get the Account Id and use that Id.

Contact__c is custom field on Lead.

 for(Lead leadObj : trigger.new) {

                if(leadObj.Contact__c == null || (leadObj.Contact__c != null && leadObj.Contact__r.Account.Id == null)) {
                    leadObj.addError('Custom Error'); .           
                }

I am getting the value for leadObj.Contact__c , but leadObj.Contact__c.Account.Id is coming null

4 Answers 4

4

You have to query those values (so, collect Contact Ids and then issue a query to retrieve their Accounts data).

Trigger Context sObjects get only their values populated by default (this is for performance reasons, Salesforce would have to load the whole record hierarchy for each trigger otherwise!)

So, have a good SOQL! (Avoid drinking and governor limits).

1
  • (As per @guy comment, and to remark what I evidenced joking in the last parenthesis, the SOQL query should be issued outside any for loop, and keep into consideration the code bulkification.)
    – MLucci
    Nov 6, 2014 at 14:00
2

In the Lead trigger you will only have the fields available that are part of the Lead object. Contact__c is a field in Lead so will be available, but AccountId is a field on Contact so will not be available.

You'd need to do an extra SOQL query to retrieve the AccountId, something like:

Id AccountId = [Select AccountId From Contact Where Id = :leadObj.Contact__c].Id;

Do take into account that this query is not bulk-proof.

You will need to first collect all contactIds in a loop, then do 1 query for all the contacts in the lead trigger (saving the contact-to-account relationships in a Map), and then check the Leads again.

1

Thank you for the responses. Somehow, I forgot the relationship won't work in the query in the case of trigger.

Below is the solution:

    Set<Id> contactIdSet = new Set<Id>();
    for(Lead leadObj : trigger.new) {
       if(leadObj.Contact__c != null) {
           contactIdSet .add(leadObj.Contact__c);    
       }   
    } 

    Map<Id, Contact> contactMap = new Map<Id, Contact>([select Id, AccountId from Contact
                                                        where Id IN :contactIdSet]);

    for(Lead leadObj : trigger.new) {
        Id acctId = contactMap.get(leadObj.Contact__c).AccountId;

        if(leadObj.Contact__c == null || acctId == null) {
            leadObj.addError('Custom Error'); .         
        }
    }
0

The other answers are technically correct, but in that case it would be much better to populate the AccountId via a formula field so you can save yourself the SOQL query in all triggers.

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.