There is a lookup relationship between two object CountParent__c
and CountChild__c
.
CountParent__c
object contains a custom field called NoOfChildRecords__c
which will count the no. of CountChild__c
records associated with it.
Required scenario is,
If user edited a CountChild__c
record and changes the value of lookup field from P2-->P1 then NoOfChildRecords__c
should be increased by 1 in P1 and decreased by 1 in P2.
all this happening on before update trigger.
if (Trigger.isUpdate && Trigger.isBefore) {
List < CountParent__c > incCount;
Set < id > triggerIds = Trigger.oldMap.keySet();
List < CountChild__c > fetchChild = [select Name, CountParent__r.name from CountChild__c where Id IN: triggerIds];
system.debug('old====' + fetchChild);
Set < id > triggerIds1 = Trigger.newMap.keySet();
List < CountChild__c > fetchChild1 = [select Name, CountParent__r.name from CountChild__c where Id IN: triggerIds1];
system.debug('new====' + fetchChild1);
List < CountParent__c > fetchParent = [select Name, NoOfChildRecords__c from CountParent__c];
for (CountChild__c a: fetchChild1) {
for (CountParent__c b: fetchParent) {
if (b.Name == a.CountParent__r.Name) {
incCount = new List < CountParent__c > ();
b.NoOfChildRecords__c = b.NoOfChildRecords__c + 1;
incCount.add(b);
}
}
}
update incCount;
}
this is the code i was trying but seems wrong.
thanks!