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
ShadowlessKickShadowlessKick 

Trigger Improvement

The trigger I wrote works but....  SOQL should not be inside the for loop.  Any suggestion of how to improve the trigger would be appreciated. Thanks.

 

trigger Aptus_OpportunityAgreement on Apttus__APTS_Agreement__c (before insert) {

	private ID theOppId = null;
	for (Apttus__APTS_Agreement__c theContract : Trigger.new )  
	{  
		if ((theContract.Apttus__Related_Opportunity__c != null) && (theContract.name.left(3) == 'SPA' || theContract.Name.left(2) == 'OT' ))
		{
			theOppId = theContract.Apttus__Related_Opportunity__c;
			Opportunity theOpportunity = [SELECT Id, Market_Code__c, Sales_Representative__c, AccountId FROM Opportunity WHERE id = :theOppId Limit 1];
			if (theOpportunity != null)
			{
			 theContract.Apttus__Account__c = theOpportunity.AccountId; 
			 theContract.APTPS_Field_Sales_Rep_Name__c = theOpportunity.Sales_Representative__c; 
			 theContract.APTPS_Market__c = theOpportunity.Market_Code__c; 
			}
		}
	} 
} //End Of Trigger

 

 

Best Answer chosen by Admin (Salesforce Developers) 
sfdcfoxsfdcfox
trigger Aptus_OpportunityAgreement on Apttus__APTS_Agreement__c (before insert) {
	Map<Id,Opportunity> opps = new Map<Id,Opportunity>();
	for (Apttus__APTS_Agreement__c theContract : Trigger.new )  
	{  
		if ((theContract.Apttus__Related_Opportunity__c != null) && (theContract.name.left(3) == 'SPA' || theContract.Name.left(2) == 'OT' ))
		{
			opps.put(theContract.Apttus__Related_Opportunity__c,null);
		}
	}
	opps.putAll([SELECT Id,Market_Code__c,Sales_Representative__c,AccountID FROM Opportunity WHERE Id IN :opps.keySet()]);
	for (Apttus__APTS_Agreement__c theContract : Trigger.new )  
	{  
		if ((theContract.Apttus__Related_Opportunity__c != null) && (theContract.name.left(3) == 'SPA' || theContract.Name.left(2) == 'OT' ))
		{
			Opportunity theOpportunity = opps.get(theContract.Apttus__Related_Opportunity__c);
			 theContract.Apttus__Account__c = theOpportunity.AccountId; 
			 theContract.APTPS_Field_Sales_Rep_Name__c = theOpportunity.Sales_Representative__c; 
			 theContract.APTPS_Market__c = theOpportunity.Market_Code__c; 
		}
	}
} //End Of Trigger