+ Start a Discussion

Help with Trigger

Hi All,


Im using this trigger:

trigger UpdateAccountSADependent on Service_Agreement__c (before update) {
Set<Id> esIds=new Set<Id>();
     for (Service_Agreement__c es : trigger.new)

     List<Account> sis=[select id, (select id from Service_Agreements__r where Master_Service_Status__c = 'Live') from Account where id in :esIds];
     for(Account si : sis) {
      if(si.service_agreements__r.size()>0) {	  
		  si.HasLiveSA__c = TRUE;
	  if(si.service_agreements__r.size()==0)  {
	  	si.HasLiveSA__c = FALSE;
   update sis;

 however, it has a  flaw, which I am hoping can easily be solved, I just cant get my head around it!


It (quite rightly, as coded) only selects Service Agreements where the Master Service Status = Live - so therefore, it sets the HasLiveSA to TRUE, but never FALSE, as for it to be FALSE, the Master Service Status would not be Live! (Hope that makes sense) so is there anyway I can get the trigger to look at all Service Agreement records and where MSS = Live - make HasLiveSA = TRUE and where MSS  = *Any This Else* make HasLiveSA = FALSE.


Hope this makes sense.


Thanks in advance.




Here is how you can loop through all of the Service Agreements and set the Account to true if you find one that is "Live", else set it to false.


// instead of filtering your Service Agreements, just query all of them.

List<Account> sis = [ select id, HasLiveSA__c, ( select id, Master_Service_Status__c from Service_Agreements__r ) from Account where id in :esIds ];


for( Account si : sis ) {

      for( Service_Agreement__c sa : si.Service_Agreements__r ) {    // this loop iterates through all Service Agreements for each Account.

            if( sa.Master_Service_Agreement__c.equals( 'Live' ) )  {

                si.HasLiveSA__c = true;



            si.HasLiveSA__c = false;




Hope that helps!




Hi Clint,


My apologies for the delayed response. Really appreciate your help with this! Cant believe I didn't think of this!


I am now getting another problem which has baffled me - so, when I have updated the trigger with your suggestion I get the following error:



Run Failures:
  Test_CountSignedNBSIDsonSI.myUnitTest System.LimitException: Too many SOQL queries: 101


Any ideas?