+ Start a Discussion

Opportunity Name changed automatically once - avoid receptions



I've just written an Apex Classe in order to modify Opportuniy Name when Stage is greater than a specific values (Order Sent). The code is the following:


public class OpportunityAutoTypeName {
 // This method updates the opportunity name at end with (FOG Client Account) w/ Account Name
 public static void addOpportunityAutoTypeName(Opportunity[] accs){
  Set<Id> accId = new Set<Id>();  
  for (Opportunity a:accs){
    if(a.AccountId != null){

  Map<Id,Account> accMap = new Map<Id,Account>([select Id, Name from Account where Id in : accId]);
  for (Opportunity a:accs){
    if(a.StageName >= 'Order Sent'){
    a.Name = a.Name+'-'+accMap.get(a.AccountId).Name+'-'+a.Number_of_hotels_this__c+'H'+'-'+a.Duration_Y__c+'Y'+'-'+a.Type_F__c;

Then I wrote a trigger that invoques this class.

All is working but I would like the name changed only once time. How can I avoid that each time the opp is updated the name changes?


Can anyone help me?







So, essentially, you only want to consider running this trigger for the objects where the stageName has been changed (and the AccountId is not null).   The typical way you do this in a trigger is to compare the old value to the new one and only process the ones you want.


List<Opportunity> oppsToProcess = new List<Opportunity>();

for (Opportunity o : Trigger.new) {

   if (o.stageName != Trigger.oldmap.get(o.id).stageName && o.AccountId != null) oppsToProcess.add(o);


if (oppsToProcess.isEmpty()) return;


Obviously, your IF statement can be as complicated as desired... so if you want to check for example, if the old stage is less than order sent and the new one is greater, then process it, then you can do that as well.  (In case the stage might flit around the "higher value" stages.)


Hope it helps, Best, Steve.