I want the following trigger to compare opportunity close date month with the custom date field month (Monthly Sales Target and Year). How can I achieve it? Basically I have created a custom object which has a lookup on the opportunity and I want the lookup field to be auto-updated in the opportunity and Custom object should pull out all related opportunities based on the criteria Closed date month. Opportunity = month in the Custom Object. Can you please guide me.

trigger TriggeronTarget on Monthly_Sales_Target__c (before insert, before update) {
Set<id>ids=new set<id>();
list<opportunity>oplst=new list<opportunity>();
    For(Monthly_Sales_Target__c trg:trigger.new){

    list<opportunity >opp =[select id,name,closeDate from opportunity where Budget_Month__c= Null AND id in:ids ];     
       for(opportunity op:opp){

for(Monthly_Sales_Target__c trg1: trigger.new){
            op.Budget_Month__c =trg1.id;
    update oplst;
  • do you want to auto populate lookup field on opportunity, based on opportunity closed date month == Monthly_Sales_Target__c,Budget_month ?
    – Navii
    May 14, 2020 at 9:57
  • Yes, I have named the Monthly Sales Target_c object lookup in the Opportunity as Budget Month. I have a date field in the Monthly sales target opportunity and opportunity close date should match the month. For ex : If the target object month is January I need all Opportuntiies with close date January to be mapped in the Monthly sales target object May 14, 2020 at 10:37

1 Answer 1


Assuming you have set the date field on Monthly_Sales_Target__c object as unique, as similar dates may give you erroneous data.

Here is the pseudo-code through which you can perform your functionality:

  1. Iterate over the list of all opportunities where status is closed(won or lost).

  2. Make a map with the key as closed date of opportunity and list of opportunities as values i.e Map> let's say date_OppsMap.

  3. Now iterate a for loop over Trigger.new and check if the date_OppsMap contains key as Monthly_Sales_Target__c date field (in your case compare the months after confirming the year). If yes, then set the Monthly_Sales_Target__c object Id in all the opportunities of the iteration.Keep the values in a list of Monthly_Sales_Target__c object.

  4. Update the list.

Note: If your are making the trigger on Monthly_Sales_Target__c object then always have a check while UPDATE, if the old date <> current date.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .