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
GRStevenBrookesGRStevenBrookes 

Help with Trigger

Hi All,

 

trigger CountArchivedSCsonSA on ServiceContract (before update) {

     Set<Id> esIds=new Set<Id>();
     for (ServiceContract es : trigger.new)
     {
        esIds.add(es.Service_Agreement__c);
     }

     List<Service_Agreement__c> sis=[select id, DEBUG_HasArchivedSC_Indicator__c, (select id from service_contracts__r) from Service_Agreement__c where id in :esIds];
    
     for(Service_Agreement__c si : sis) {
      
      si.DEBUG_HasArchivedSC_Indicator__c  = si.service_contracts__r.size();
      si.Stage__c = si.service_contracts__r.Stage__c
  }
  update sis;
}

 The above trigger is quite simple - provides a count of records on a related list and updates a field (DEBUG_HasArchivedSC_Indicator__c) on the parent object.

 

However , when i add  si.Stage__c = si.service_contracts__r.Stage__c it dosnt work - i get : 

 

Save error: Invalid foreign key relationship: Service_Agreement__c.service_contracts__r

 

Dont quite understand why - as i am not doing anything different from the line above it, part from Instead of counting the records, I want to pass the value of the a field on one of the records back to the parent object. NB. Their will only ever be 1 record of type Service_Contract__c

 

Thanks in advance for your help.

 

Steve 

shruthishruthi

Try this!

 

trigger CountArchivedSCsonSA on ServiceContract (before update) {

     Set<Id> esIds=new Set<Id>();
     for (ServiceContract es : trigger.new)
     {
        esIds.add(es.Service_Agreement__c);
     }

     List<Service_Agreement__c> sis=[select id, DEBUG_HasArchivedSC_Indicator__c, (select id, Stage__c from service_contracts__r) from Service_Agreement__c where id in :esIds];
    
     for(Service_Agreement__c si : sis) {
      if(si.service_contracts__r.size()>0) {	  
		  si.DEBUG_HasArchivedSC_Indicator__c  = si.service_contracts__r.size();
		  si.Stage__c = si.service_contracts__r[0].Stage__c;
	 }	
  }
  update sis;
}

 

Hope it helps. Let me know if you face any more issues.