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
MrKenMrKen 

Trigger to autocreate record in related list

Hello,

 

I searched around the forum/documentation to do this simple trigger update but didn't find anything.

 

What I have:  2 objects-  Site Location & Opportunity.  Site Location has a lookup to the opportunity.  

 

What I'm trying to do: Since every opp in our instance should have a site location, I'd like for a site location to be automatically created (and linked) everytime a new opportunity is created.  

 

Here's my code that I have so far: 

 

 

trigger createSiteLocations on Opportunity (after insert) {

for (Opportunity opp : trigger.new) {
	
		Site_Location__c sl = new Site_Location__c();		
		
		insert sl;
	}
	
	
}

 

This is not working...any ideas/help?

 

 

Best Answer chosen by Admin (Salesforce Developers) 
gm_sfdc_powerdegm_sfdc_powerde

You are not populating the lookup value on Site location.  Also, collect site locations in a list and insert them in bulk to avoid hitting governor limits.  Something like this would do -

 

 

trigger createSiteLocations on Opportunity (after insert) {

List<Site_Location__c> siteLocations = new List<Site_Location__c>();
for (Opportunity opp : trigger.new) {
	
		Site_Location__c sl = new Site_Location__c();		
		sl.Opportunity__c = opp.Id;  //Change it to use the API name you used for lookup.
		siteLocations.add(sl);
	}

insert siteLocations;
	
	
}

 

 

All Answers

gm_sfdc_powerdegm_sfdc_powerde

You are not populating the lookup value on Site location.  Also, collect site locations in a list and insert them in bulk to avoid hitting governor limits.  Something like this would do -

 

 

trigger createSiteLocations on Opportunity (after insert) {

List<Site_Location__c> siteLocations = new List<Site_Location__c>();
for (Opportunity opp : trigger.new) {
	
		Site_Location__c sl = new Site_Location__c();		
		sl.Opportunity__c = opp.Id;  //Change it to use the API name you used for lookup.
		siteLocations.add(sl);
	}

insert siteLocations;
	
	
}

 

 

This was selected as the best answer
MrKenMrKen

:smileyhappy:

 

Genius!! Thanks for your help.  I see how the above breaks down...going to start creating more to help with processes!!

 

Thanks again!