function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Nevin O'Regan 3Nevin O'Regan 3 

Automatically Relate Child Objects To Parent Object Based On Criteria

I am looking for some help with a trigger. 

I have created a custom object Sales_Order_Line__c which has a Parent Object Exchange_Rate__c. In Sales_Order_Line__c there is a date field called Shipment_Date__c and in the Exchange_Rate__c object there are two date fields called Start_Date__c and End_Date__c.

If the Shipment Date falls within the Start Date and End Date of the Exchange_Rate__c object I would like it to automatically relate to this object.

Can anyone help me with this?
v varaprasadv varaprasad
Hi Nevin,

Please check once below sample code : 
 
Trigger updExchange_Rate on Sales_Order_Line__c  (before insert, before Update){
     
	 List<Date> dates = new List<Date>();

	 for(Sales_Order_Line__c sr : trigger.new){
	    if(sr.Shipment_Date__c != null)
		
		 Exchange_Rate__c exr = [select id from  Exchange_Rate__c where Start_Date__c < Shipment_Date__c and End_Date__c > Shipment_Date__c limit 1];
		 
		 if(exr != null)
		 // Add parent ExchangeRate__c API Name below
		 sr.ExchangeRate__c = exr.id;
	    }
    
    }

Hope this helps you!
If my answer helps resolve your query, please mark it as the 'Best Answer' & upvote it to benefit others.

Thanks
Varaprasad
@For SFDC Support: varaprasad4sfdc@gmail.com
Blog: http://salesforceprasad.blogspot.com/

Salesforce latest interview questions  :
https://www.youtube.com/channel/UCOcam_Hb4KjeBdYJlJWV_ZA?sub_confirmation=1

 
Nevin O'Regan 3Nevin O'Regan 3
Thank you @v varaprasad, I will try this and let you know if it works.
Nevin O'Regan 3Nevin O'Regan 3
Hi Varaprasad,

I have tried your code and I'm getting a bunch of errors.

User-added image
Raj VakatiRaj Vakati
try this .. this code is not bukfiled
 
Trigger updExchange_Rate on Sales_Order_Line__c  (before insert, before Update){
     
	 List<Date> dates = new List<Date>();

	 for(Sales_Order_Line__c sr : trigger.new){
	    if(sr.Shipment_Date__c != null)
		
		 Exchange_Rate__c exr = [select id from  Exchange_Rate__c where Start_Date__c < :sr.Shipment_Date__c and End_Date__c > :sr.Shipment_Date__c limit 1];
		 
		 if(exr != null)
		 // Add parent ExchangeRate__c API Name below
		 sr.ExchangeRate__c = exr.id;
	    }
    
    }