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
Ricky 007Ricky 007 

trigger to ensure that there is no duplicate start or end date

Hi, I am new to salesforce and i am having a hard time to create a trigger for this requirement.

I have two object AGREEMENT and CAR, they have a lookup between them where CAR is parent.
The requirement is like this, if two AGREEMENT record has same CAR record then the 2 records of AGREEMENT should have different START DATE or END DATE.

for ex. if AGREEMENT1 and AGREEMENT2 both have SUZUKI as their parent then, then START DATE or END DATE(atleast one Date) should be different from another.

Any help would be appreciated.
Thanks in advance.
v varaprasadv varaprasad
Hi Ricky,

Please check below sample code : 
 
trigger AgrrementsDateShouldbedifer on AGREEMENT__c(before insert,before update){
  set<id> carIds = new set<id>();

   for(AGREEMENT__c c : trigger.new){
   if(c.car__c != null && c.startdate__c != null && c.enddate__c != null){
        carIds.add(c.car__c);
      } 
   
   }

   list<AGREEMENT__c> existingAgrs = [select id,startdate__c,enddate__c from AGREEMENT__c
   where car__c in : carIds AND startdate__c != null AND enddate__c != null];
   set<date> startdates = new set<date>();
   set<date> enddates = new set<date>();
   
   for(AGREEMENT__c ex : existingAgrs){
      startdates.add(ex.startdate__c);
	  enddates.add(ex.enddate__c);
   }
   
  for(AGREEMENT__c c : trigger.new){
     if(startdates.contains(c.startdate__c) && enddates.contains(c.enddate__c)){
	   c.addError('startdate and dates are already exist in othere agrrements add new one');
	 } 
  
     }

}



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 Salesforce Project Support: varaprasad4sfdc@gmail.com

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