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
Ali MeyerAli Meyer 

Trigger to insert ID into lookup field

Hello,

 

I have a really basic issue: When a specific boolean field = true on a contact object, I want the ID of that contact to populate into a field on the associated Account object. I don't think this should be too hard but I am really new to Apex so I appreciate all the help I can get!

 

here's the code I have so far:

trigger Secondary on Contact (after update) {
List<Contact> cons = new List<Contact>();
    List<Contact> consToSecondary = new List<Contact>();
    
    for(Contact c:trigger.new){
        if(c.SecCon_Checkbox__c != null && c.cv__Head_of_Household__c != true){
            cons.add(c); 
        }
    }
    
    for(Contact c: cons){
    c.Account.cv__Secondary_Contact__c = c.Id;
    consToSecondary.add(c);
    }
    
    update consToSecondary;
}

 The code compiles alright but when I try to test it I get this error: 

 

Error:Apex trigger Secondary caused an unexpected exception, contact your administrator: Secondary: execution of AfterUpdate caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.Secondary: line 12, column 1

 

Any help is appreciated, and thank you!

Best Answer chosen by Admin (Salesforce Developers) 
kriskkrisk

You cannot reference an Account from Contact and the variable assignment is giving account a null object. The best bet is to get the Account object using AccountId reference from Contact object and update Account object seperately. Below is the code that works

 

trigger SecondaryTrig on Contact (after update) {
List<Contact> cons = new List<Contact>();
List<Account> accs = new List<Account>();

for(Contact c:trigger.new){
if(c.SecCon_Checkbox__c != null && c.cv__Head_of_Household__c != 'true'){
system.debug('here');
cons.add(c);
}
}

for(Contact c: cons){
Account a = [select a.Id from Account a where a.Id=:c.AccountId];
system.debug(a);
a.cv__Secondary_Contact__c = c.Id;
accs.add(a);
}

update accs;
}

All Answers

kriskkrisk

You cannot reference an Account from Contact and the variable assignment is giving account a null object. The best bet is to get the Account object using AccountId reference from Contact object and update Account object seperately. Below is the code that works

 

trigger SecondaryTrig on Contact (after update) {
List<Contact> cons = new List<Contact>();
List<Account> accs = new List<Account>();

for(Contact c:trigger.new){
if(c.SecCon_Checkbox__c != null && c.cv__Head_of_Household__c != 'true'){
system.debug('here');
cons.add(c);
}
}

for(Contact c: cons){
Account a = [select a.Id from Account a where a.Id=:c.AccountId];
system.debug(a);
a.cv__Secondary_Contact__c = c.Id;
accs.add(a);
}

update accs;
}

This was selected as the best answer
Ali MeyerAli Meyer

It works perfectly. Thank you!