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
Jean-LucJean-Luc 

Use an Opportunity trigger to sync the value of the Stage with the value of a custom picklist

Hello
In the Opportunity object, I created three record types and two custom fields:
- a picklist "Opportunity Sub-type" controlling 
- a picklist "Funnel Stages" with in fact exactly the same values as the picklist standard field "StageName"
The purpose is to limit in the different record types the stages to use for each Opportunity Sub-Type.
As the field StageName is mandatory on Opportunity and not possible to define field dependencies with, I created a trigger to sync the StageName value when the same one is selected in the "Funnel_Stages__c" picklist.
------------
trigger UpdateSource on Opportunity (after update) 
{                                                                      
  List<Opportunity> opportunitiesToUpdate = new List<Opportunity>();     
  for(Opportunity currOpportunity : trigger.new) 
  {
    currOpportunity.StageName= currOpportunity.Funnel_Stages__c;          
    leadsToUpdate.add(currOpportunity);                                       
  }
  update opportunitiesToUpdate;                                        
}
--------------------
Not error when compiled but well when activated as I had thefollowing error message on the Opportunity page:
-------------------
Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger UpdateSource caused an unexpected exception, contact your administrator: UpdateSource: execution of AfterUpdate caused by: System.FinalException: Record is read-only: Trigger.UpdateSource: line 6, column 1
-----------------
Can somebody help me?
Thanks already.
Best regards
Jean-Luc
Best Answer chosen by Jean-Luc
Jean-LucJean-Luc
Hi
Thank you very much for the solution. 
Fully working. 
Best regards
Jean-Luc

All Answers

sathishkumar periyasamysathishkumar periyasamy
@jean, use before update instead of after update. your are trying to update same record before data commit to database. if you want to change some value on the same record please try to use WorkflowRule or Process Builder or Before Insert/Update Trigger.

If you realy want to use trigger please find below code :

trigger UpdateSource on Opportunity (before update)
{               
  for(Opportunity currOpportunity : trigger.new)
  {
    currOpportunity.StageName= currOpportunity.Funnel_Stages__c;   
  }                                   
}
Jean-LucJean-Luc
Hi
Thank you very much for the solution. 
Fully working. 
Best regards
Jean-Luc
This was selected as the best answer
Jean-LucJean-Luc
But the trigger is not working when I'm creating a new Opportunity!?!
I added (before insert,before update) but it's not working. 
Thanks already