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
Mark Thompson 7Mark Thompson 7 

Need a Trigger on Account Object to pull Opportunity Object field info

Because opps is an child relationship to Account.  I am unable to use standard formula to create a field on account object that would fill in with information from a field on opportuntiy.  I was told by support that I would need to use a trigger but haven't written one before.  Can someone help with the code and I'll fill in the API fields needed?
claperclaper
Hi Mark, triggers are very simple to write here is some official documentation https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_qs_HelloWorld.htm

Even though I don't the real name of your fields here is a sample trigger that might work:
trigger AccountUpdate on Account  (before update) {
	Map<AccountId,Opportunity> opportunityByAccountId = new Map<AccountId,Opportunity>();
	
	for(Opportunity opps : [Select AccountId, Needed_Field__c from Opportunity where accountid IN: Trigger.new])
	{
		opportunityByAccountId.put(opp.accountid,opp);
	}
	
	for(Account thisAcc : trigger.new)
	{
		if(opportunityByAccountId.containsKey(thisAcc.Id))
			thisAcc.Field_In_Account__c = opportunityByAccountId.get(thisAcc.Id).Needed_Field__c;
	}

}
In the above code, i assume the following:
  1. Either all opportunities related to an account will have the same value in the Need_field__c,
  2. or all account might only have one and only one oppportunity

Also keep in mind the following:
  • To create a trigger you must do it in a Sandbox enviroment first
  • To deploy a trigger to product you must have at least 1% of test coverage on that trigger; this is accomplished writting a test class
  • To succesfully deploy you must have at least 75% coverage in all you classes.
Another way to approach this issue is to create a Workflow rule on the Opportunity, so every time the Need_Field__c is updated, then update it's parent account field.