I have custom object People__c
that has lookup field Married__c
to the same object (People__c
) and I want to create a trigger for auto update after insert and update. For example, if we insert new People__c
(husband) or modify it and add in lookup field another People__c
(wife) then wife must have in her lookup field automatically added husband and conversely.
I've written the next code but it doesn't work. What could I try instead?
trigger InsertUpdateMarried on People__c (after insert, after update) {
Set<Id> peopleMarriage = new Set<Id>();
for(People__c people : trigger.New) {
peopleMarriage.add(people.Married__c);
}
Map<Id,People__c> matchingPeopleMap = new Map <Id,People__c>();
for (People__c people : [Select Id, Married__c From People__c Where Id IN :peopleMarriage]) {
matchingPeopleMap.put(people.Id, people);
}
List<People__c> peoplesToUpdate = new List<People__c>();
for(People__c people : trigger.New) {
if (matchingPeopleMap.containsKey(people.Id))
{
people.Married__c = matchingPeopleMap.get(people.Id).Id;
peoplesToUpdate.add(people);
}
}
update peoplesToUpdate;
}
Best Answer
This can all be reduced to the following. No queries needed as you did not ask to check if the field on the related person was already populated or not
Note The block of updating records that are in the trigger. You will need to figure out how to handle People in the trigger that are related to people in the trigger
You will need to handle recursion since you are updating records that are part of the same object. Best to move all logic to a class but the above will give you an idea of what you need to do
Basically what it does is
Married__c
valueMarried__c
Married__c
of that #2 record to theId
of the matching trigger record