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
Sangeeta BhatiaSangeeta Bhatia 

Trying to update a field on a record if that record is selected in lookfield on another object.

Hi all I am very new to Apex code.I am able to do basic stuff but really struggling w this. Any help or code sample is appreciated.
Scenario- I have a custom object say DMContact, in that I have a contact look up field.
When any contact is selected in a DMContact record I want to flag that contact as being used in the DMContact.
So basically I want to retrieve the ID of the contact records selected in the look up field on the DNContact record, then go that contact record and update a checkbox field on Contact object called 'DMContact'.
Best Answer chosen by Sangeeta Bhatia
Shaijan ThomasShaijan Thomas
1. Create a trigger in DMContact.
2. Get the contact id
3. Search for the contact (select DMContact from contact where id = DMContact.ID)
4. Check DM Contact (checkbox) = true;
5. update contact
Let know your thoughts
Shaijan Thomas
 

All Answers

Shaijan ThomasShaijan Thomas
1. Create a trigger in DMContact.
2. Get the contact id
3. Search for the contact (select DMContact from contact where id = DMContact.ID)
4. Check DM Contact (checkbox) = true;
5. update contact
Let know your thoughts
Shaijan Thomas
 
This was selected as the best answer
Sangeeta BhatiaSangeeta Bhatia
Thanks Shaijan. This is helpful. Gives me some clue to start with. If you have sample code for any of these steps will be very helpful. Thanks.
Sangeeta BhatiaSangeeta Bhatia
OK here is what i came up with. And it worked!! OMG I am so surprised at myself that i was able to get this to work.

// Update Contact field: "DMContact" to TRUE when a new DMAPP__DM_Political_Map_Contact__c record is inserted. 
// There is a Contact look up field record on DMAPP__DM_Political_Map_Contact__c.

trigger UpdateDMContactCheckbox on DMAPP__DM_Political_Map_Contact__c (after insert) {
 
// Will store lookup Contact record ID
map< id, contact > contacts = new map< id, contact >();
 
// Create trigger for new DMAPP__DM_Political_Map_Contact__c record
for(DMAPP__DM_Political_Map_Contact__c record:trigger.new)        
 
     // Update checkbox field on the lookup Contact record to TRUE    
     contacts.put(record.DMAPP__Contact__c, new contact(id=record.DMAPP__Contact__c, DM_Contact__c = TRUE));      
 
update contacts.values();  
 
}