You need to sign in to do that
Don't have an account?

Trigger to update the value from one object to another object without relationship
My scenario is to calculate the holidays for an opportunity. For this i have created an custom field(DateType: Integer) in opportunity called "Holidayslist__c"(This field i want to display no of holidays).
1.If my opportunity is in "Open" , i want to calculate the holidays between the opportunity CreatedDate field to TODAY.
2.If Opportunity is "Closed", i want to calculate the holidays between the CreatedDate field to ClosedDate.
I wrote a trigger but its not working and it will hit the governer limit. Can anyone give me suggestion how to do this.
Thanks In Advance.
trigger testholidays on Opportunity (before insert, before update) { List<opportunity> lstOpp = new List<opportunity>(); List<opportunity> lstOppToUpdate = new List<opportunity>(); Map<Date,Integer> mapActivDateToCount = new Map<Date,Integer>(); Set<Date> setDateOppCreated = new Set<Date>(); list<opportunity> opp1 = [select id,Name,CreatedDate,Holidayslist__c from opportunity where IsClosed =False]; for(Opportunity objOpp : opp1 ) { lstOpp.add(objOpp); setDateOppCreated.add(objOpp.CreatedDate.date()); } for(Holiday objHoilday : [ SELECT Id, ActivityDate FROM Holiday WHERE ActivityDate < TODAY AND ActivityDate >: setDateOppCreated ]) { Date dt = objHoilday.ActivityDate; if(mapActivDateToCount.containsKey(dt)) { mapActivDateToCount.put(dt, mapActivDateToCount.get(dt)+1); } else { mapActivDateToCount.put(dt, 1); } } // I am not getting any way to avoid for inside for . for(Opportunity objOpp : lstOpp) { opp1[0].Holidayslist__c = 0; for(Date dtActivity : mapActivDateToCount.keySet()) { if(dtActivity < objOpp.CreatedDate.date()) { opp1[0].Holidayslist__c += mapActivDateToCount.get(dtActivity); } } lstOppToUpdate.add(objOpp); } system.debug('=====lstOppToUpdate===='+lstOppToUpdate); Database.update(lstOppToUpdate, true); }
All Answers
Please try below modified code :
Hi Jetha SF
Thank you for your reply. It's throwing an error like "Variable does not exist: setDateOppCreated". Again we want to write an query for opportunity ?
Hi Jetha SF
Thank you for your reply. But its throwing an error " Variable does not exist: checkRecursive". Can you please explain why you used that one.
This class is used to stop recurssive trigger.
Please create below class in your Org and then run the code :
Thank you its working