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
PlainviewPlainview 

Make Apex Trigger fire only once.

I have an Apex Trigger in our Sandbox that is designed to assign leads to the Sales Rep. who owns the related Account. The requirements are as follows:

1. Automate the routing of leads for existing accounts to the account owner.
2. If a duplicate account/company exists and each have different owners, any new leads created should be assigned to our Sales Manager.

Example:

ABC Company has an existing account where the Account Owner is John Smith
ABC Company has a 2nd existing account where the Account Owner is Jane Doe
A new Lead is submitted for ABC Company
Expected Result: Assign the Account Owner to Sales Manager by default; she will be the tie breaker.

The code I developed:

rigger addAccount on Lead (before Insert, before Update){
  
  final String marjorieUserId = '00500000006pFs8';
  
  List<String> companies = new List<String>();
  
  for (Lead l : trigger.new){
    if (String.isEmpty(l.company)) continue; 
    if (l.ownerId != null) continue;
    companies.add(l.company);
  }

  if (companies.isEmpty()) {
    // we can not pull any accounts without knowing their names
    return ;
  }

  final List<String> nameValues = new List<String>();
  
  for (String companyName : companies) {
    nameValues.add('(Name = \'' + String.escapeSingleQuotes(companyName) + '\')');
  } 

  final List<Account> leadAccountIds = Database.query('Select Id, OwnerId, Name FROM Account WHERE ' + String.join(nameValues, ' OR '));  

  Map<String, Id> acctNameId = new Map<String, Id>();
  Map<String, Id> acctNameOwner = new Map<String, Id>();
  Map<String, Boolean> duplicateAccountMap = new Map<String, Boolean>();
      
  for (Account a : leadAccountIds) {
      acctNameId.put(a.name, a.Id);
      acctNameOwner.put(a.name, a.ownerId);
      if (duplicateAccountMap.containsKey(a.Name)) {
          duplicateAccountMap.put(a.name, true);
      } else {
          duplicateAccountMap.put(a.name, false);
      }
        
  }
  
  for (Lead l2 : trigger.new){
    
    if ((l2.ownerId != null)) {
      //ReportingService.notifyEngineers('lead already has an owner', lead.Email + ' : ' + lead.ownerId);
      continue;
    }
    
    if (marjorieUserId.equals(l2.ownerId)) {
      ReportingService.notifyEngineers('lead is assigned to Marjorie', 'at addAccount triggah line 27');
      continue;
    }
    if(acctNameId.containsKey(l2.company)) {
        l2.Account__c = acctNameId.get(l2.company);
      if (duplicateAccountMap.get(l2.company)) {
        ReportingService.notifyEngineers('assigning lead to Marjorie', 'at addAccount triggah line 33');
            l2.ownerId = marjorieUserId; // Marjorie
        } else {
          if (marjorieUserId.equals(l2.company)) ReportingService.notifyEngineers('lead is assigned to Marjorie', 'at addAccount triggah line 36');
            l2.ownerId = acctNameOwner.get(l2.company);
        }
    
    }
      
  }

}


The issue is that the Trigger is firing again when the Sales Manager tries to reassign the new lead to it's corresponding Account owner; it blocks her out and she is unable to reassign the lead.

I would like to add logic to the code that prevents the Trigger from firing twice.

Thanks,
Julien

BalajiRanganathanBalajiRanganathan
this should help to avod trigger firing twice

https://help.salesforce.com/apex/HTViewSolution?id=000005328&language=en_US

 
SarfarajSarfaraj
Hi Julien

If I understood your requirement correctly, you want to prevent this trigger to fire when you are updating the owner manually. And this condition arises only for Update event.
In my opinion you have to use Trigger.Old or Trigger.OldMap to get the corresponding old value of the Owner field and compare it with current value.
1. If the values are different then it is a manual update.
2. If the values are same it is the case when the trigger should update it.

Also please double check if you really need this trigger in after update event. I think auto assignment is required only when it is created. Please let me know if this helps you to solve your issue.

--Akram
Suneel#8Suneel#8
I guess you dont want the trigger to be fired when current logged in user is Manager.You to put all of your logic in the below if block

  final String marjorieUserId = '00500000006pFs8';
  if(!String.valueOf(UserInfo.getuserId()).contains(marjorieUserId)){
PlainviewPlainview
Thanks Everyone. Looking at your suggestions and will get back to you.