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
Rick RoseRick Rose 

Trigger to update field on a lookup item

On my opportunity I have a lookup to a contact record. When I save an opportunity I want to update a checkbox on the contact record. 

here is my code:


trigger flagDonor on Opportunity (after insert) {
    for (Opportunity opp : Trigger.new){
      
       //Check and see if there is an individual donor attached to this donation      
       if(opp.Individual__c!=null){
      
           //update the donor contact to flag as a financial donor
           opp.Individual__r.financial_donor__c = TRUE;
        }       
    }
}


but I'm getting this error:
System.NullPointerException: Attempt to de-reference a null object: Trigger.flagDonor: line 8, column 1
Best Answer chosen by Rick Rose
ShashForceShashForce
Hi Rick,

Here is some sample code which implements the above suggestion:

trigger flagDonor on Opportunity (after insert) {
    for (Opportunity opp : Trigger.new){    
       //Check and see if there is an individual donor attached to this donation      
       if(opp.Individual__c!=null){
           //update the donor contact to flag as a financial donor
           contactIds.add(opp.Individual__c);
        }       
    }
	for(contact con:[select financial_donor__c from contact where Id IN :contactIds]){
		Contact contact = new Contact();
		contact.Id = con.Id;
		contact.financial_donor__c = TRUE;
		contactlist.add(contact);
	}
	update contactlist;
}

If this answers your question, please mark this as the Best Answer for this post, so that others can benefit from this post.

Thanks,
Shashank

All Answers

Nilesh Jagtap (NJ)Nilesh Jagtap (NJ)
You need to explicitly query contact object with required fields as you will only have the id available for Individual__c in trigger. Also you will need to update the contact record in trigger explicitly.

Hope this will help :)

-N.J
ShashForceShashForce
Hi Rick,

Here is some sample code which implements the above suggestion:

trigger flagDonor on Opportunity (after insert) {
    for (Opportunity opp : Trigger.new){    
       //Check and see if there is an individual donor attached to this donation      
       if(opp.Individual__c!=null){
           //update the donor contact to flag as a financial donor
           contactIds.add(opp.Individual__c);
        }       
    }
	for(contact con:[select financial_donor__c from contact where Id IN :contactIds]){
		Contact contact = new Contact();
		contact.Id = con.Id;
		contact.financial_donor__c = TRUE;
		contactlist.add(contact);
	}
	update contactlist;
}

If this answers your question, please mark this as the Best Answer for this post, so that others can benefit from this post.

Thanks,
Shashank
This was selected as the best answer