You need to sign in to do that
Don't have an account?
Update child when child from same parent is inserted.
Hi Team,
Parent: Opportunity
Child: Opportunity Member
I want to update an existing child of an opportunity if a field with the name primary is true on the existing child(Primary child) when a new child is inserted. We can only have one primary member(child record ) for the opportunity. There is a field Amount on the Opportunity Member object and I want to update this field by subtracting the Amount of New Opportunity member(that we are inserting) from Primary Opportunity Member(an existing record).
My Code is working fine for a single record but not working as expected for bulk operation. Please help
Thank you
public class OppotunityMemberTriggerhandler{ public static void afterInsert(List<Opportunity_Member__c> newoppMember){ Set<Id> oppIdSet = new Set<Id>(); List<Opportunity_Member__c> memberList = new List<Opportunity_Member__c>(); Map<id,Opportunity_Member__c> oppMemberMap = new Map<id,Opportunity_Member__c>(); List<Opportunity_Member__c> updatedMemberList = new List<Opportunity_Member__c>(); for(Opportunity_Member__c newMember : newoppMember){ oppIdSet.add(newMember.Opportunity__c); } if(oppIdSet.size()>0){ memberList = [SELECT id,Amount__c,Opportunity__c,Primary__c FROM Opportunity_Member__c WHERE Opportunity__c IN :oppIdSet AND Primary__c = True ]; } for(Opportunity_Member__c member : memberList){ oppMemberMap.put(member.Opportunity__c,member); } for(Opportunity_Member__c oppMember : newoppMember){ if(oppMember.Primary__c == False){ for(Opportunity_Member__c primaryMember : memberList){ primaryMember.Amount__c = oppMemberMap.get(oppMember.Opportunity__c).Amount__c - oppMember.Amount__c; updatedMemberList.add(primaryMember); } } } update updatedMemberList; } }
Line No 29
oppPriMem.Opportunity__c = oppMember.Opportunity__c;
Thanks,
Maharajan.C
All Answers
Try the below changes in your code:
Thanks,
Maharajan.C
Thank for your help but I am getting an error at this line 28 oppPriMem.Opportunity__c = oppMember.Opportunity__c;
Apex trigger OppMemberTrigger caused an unexpected exception, contact your administrator: OppMemberTrigger: execution of AfterInsert caused by: System.SObjectException: Field is not writeable: Opportunity_Member__c.Opportunity__c: Class.OppotunityMemberTriggerhandler.afterInsert:
Regards,
Manu
Line No 29
oppPriMem.Opportunity__c = oppMember.Opportunity__c;
Thanks,
Maharajan.C