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
valentijnnkvalentijnnk 

Simple (before delete) Trigger

Hi there,

I have two objects: (the standard) Contact and a CustomObject. The relationship between the two is a lookup-field on the Contact, named "CustomObjectID". 
I have a checkbox on the CustomObject-record; this checkbox shows whether a Custom Object has a Contact related to it.

Now, when I delete a Contact, I want the checkbox on the related Custom Object to be unchecked.

I currently use this apex trigger:

trigger CustomObjectDelete on Contact (before delete) {
for (Contact c : Trigger.old) {
c.CustomObject__r.Checkbox__c = false;
  }
}

But it gives error:  "System.NullPointerException: Attempt to de-reference a null object:"

Many many thanks in advance !

KR, Valentijn
Best Answer chosen by Admin (Salesforce Developers) 
JuanBessJuanBess

Hi, the problem is that the trigger doesn't drill into the relationships. So you have to select them manually. Will be something like this:

trigger CustomObjectDelete on Contact (before delete) {
   Set<Id> customObjectIds = new Set<Id>();
   for (Contact c : Trigger.old) {
      customObjectIds.add(c.CustomObject__c);
   }

   // I do the update this way to avoid hit limits (mass update)
   for (List<CustomOjbect__c> iterList : [select id, Checkbox__c from CustomObject__c where id in: customObjectIds]) {
      for (CustomObject__c iter : iterList){
         iter.Checkbox__c = false;
      }
      update iterList;
   }
}

 

Let me know if that was what you were looking for.

Regards,

J.

All Answers

kiranmutturukiranmutturu

in trigger instance you cant access the refernce fields .. u need to get all the deleted contacts first and get all the related custom object records and update as u required...

valentijnnkvalentijnnk

Thanks ! That makes sense.

Is it difficult to create a trigger like that (including the queries) ? Do you have any documentation/links on this ?

 

Many thanks in advance !

JuanBessJuanBess

Hi, the problem is that the trigger doesn't drill into the relationships. So you have to select them manually. Will be something like this:

trigger CustomObjectDelete on Contact (before delete) {
   Set<Id> customObjectIds = new Set<Id>();
   for (Contact c : Trigger.old) {
      customObjectIds.add(c.CustomObject__c);
   }

   // I do the update this way to avoid hit limits (mass update)
   for (List<CustomOjbect__c> iterList : [select id, Checkbox__c from CustomObject__c where id in: customObjectIds]) {
      for (CustomObject__c iter : iterList){
         iter.Checkbox__c = false;
      }
      update iterList;
   }
}

 

Let me know if that was what you were looking for.

Regards,

J.

This was selected as the best answer
valentijnnkvalentijnnk

GREAT !!! THANKS !!!!

JuanBessJuanBess

No problem :)

J.