I have a requirement in which I have to create a custom lookup field on lead object which selects the account  Account__c and during the lead to account conversion I have to map the field with 'Parent Account' field of  the account which is a standard field.So i am trying to write the code  on before insert trigger that maps the custom lookup field of lead to the standard field of account.  trigger populateParentAccount on Lead(after Update) {     List&lt;Account&gt; newAccList = (List&lt;Account&gt;)Trigger.New;       List&lt;Account&gt; updateAccontList = new List&lt;Account&gt;();       Set&lt;Id&gt; accountIds = new Set&lt;Id&gt;();   system.debug('newAccList: ' + newAccList);           for(Lead record: [SELECT ConvertedAccountId, Agency_Account__c FROM Lead WHERE ConvertedAccountId = :newAccList]) {         // Avoid multiple leads with same account          system.debug('ConvertedAccountId:' + record.ConvertedAccountId);         system.debug('record:' + record);         if(!accountIds.contains(record.ConvertedAccountId)) {            updateAccontList.add(new Account(Id=record.ConvertedAccountId, ParentId=record.Agency_Account__c));           accountIds.add(record.ConvertedAccountId);        }       }       if(!updateAccontList.isEmpty()){           update updateAccontList;       }     }
122202
I have a requirement in which I have to create a custom lookup field on lead object which selects the account Account__c and during the lead to account conversion I have to map the field with 'Parent Account' field of the account which is a standard field.So i am trying to write the code on before insert trigger that maps the custom lookup field of lead to the standard field of account.  trigger populateParentAccount on Account (before Insert){     List&lt;Lead&gt; convertedLeads=[SELECT Id, ConvertedAccountID,Agency_account__c FROM Lead WHERE IsConverted=True AND ConvertedAccountId IN :trigger.new];     Map&lt;ID,ID&gt; acctParentMap=new Map&lt;ID,ID&gt;();      for (lead l: convertedleads){         acctParentMap.put(l.ConvertedAccountId,l.Agency_account__c);     }      for (account a:trigger.new){      if (acctParentMap.containsKey(a.Id)){       a.ParentId = acctParentMap.get(a.Id);       }     } }   But It is not working.. Please help..
62150
I need to be able to detect that the trigger execution is happening because of a workflow field update. There is a suggestion in the cookbook:  But this solution is not properly bulkified. If my batch of records is split up (200, 100, 50 whatever the server decides) the 2nd to nth batches are not processed correctly because the flag has already been set. The second part of the problem is: This is part of a managed package. I have no control of the customer's workflow rules, supporting and configuring a flag/last changed field on a record is not realistic, our company doesn't have the support resources to be walking each customer through the configuration. Has anyone been able to solve this problem for large batches of records? Edit (In Response to Calebs Answer) Separate trigger batches do not run in separate contexts trigger AccountTriggerContext on Account (before insert) {     System.debug('counter='+TriggerContextCounter.getCounter()); }  . global without sharing class TriggerContextCounter {      private static Integer counter = 0;          public static Integer getCounter() {         Integer value = counter;         counter++;         return value;     }      private static testMethod void testTriggerContexts() {         List&lt;Account&gt; accounts = new List&lt;Account&gt;();         for(Integer i = 0; i &lt; 250; i++) {             accounts.add(new Account(Name='testTriggerContexts: ' + i));         }         insert accounts;     } }  Unit test debug messages  USER_DEBUG|[2]|DEBUG|counter=0 USER_DEBUG|[2]|DEBUG|counter=1  Both counters should have been 0 if the batches were running in separate contexts Edit Further explanation of background for @Ralph This is a generalized explanation, but when certain conditions are met, some date fields on other objects are updated. The trigger runs and updates the dates. If a workflow rule causes a field update on the object, the same trigger is run again and the dates on the other objects are updated for a second time. And because this is an increment operation the dates on the other objects are off by a factor of 2.
78345
Code  trigger CreatePerson on Contact (before insert) {     RecordType personAccountRecordType =  [SELECT Id FROM RecordType WHERE Name = 'Person Account' and SObjectType = 'Account'];      Map&lt;Contact, Account&gt; accounts = new Map&lt;Contact, Account&gt;();    for(Contact record: Trigger.new) {        if(record.AccountId == null) {            Account newPersonAccount = new Account();            newPersonAccount.FirstName = record.FirstName;            newPersonAccount.LastName = record.LastName;            newPersonAccount.RecordType = personAccountRecordType;             accounts.put(record, newPersonAccount);        }    }     insert accounts.values();     for(Contact record: Trigger.new) {        if(record.AccountId == null) {            record.AccountId = accounts.get(record).Id;        }    } }   Error  Validation Errors While Saving Record(s) There were custom validation error(s) encountered while saving the affected record(s). The first validation error encountered was "Can not select a person account".   How can I associate the recently created Person account with the Contact?
99911
I wrote the following trigger and I'm getting the error :     Illegal assignment from Schema.SObjectField to String   But I don't know how to fix it. I wrote a similar trigger before and didn't have any issues.   trigger AccountDuplicates on Account (before insert, before update) {  for (Account myaccount : Trigger.new) {         List &lt;Account&gt; dupes = [SELECT Name FROM Account WHERE Name = :(myaccount.Name)];          if (dupes.size() &gt; 0) {            myaccount.Duplicate_Account__c = Account.name;         }     } }   The purpose of the trigger - when a new account is created that matches the name of an existing account, put the existing account's name into the "Duplicate Account" field.
120449
I am getting this error with the code below. I've looked into the other cases on here. In my case I am referring to a relationship name (__r) which I am assuming is pulling correctly. It's a field which is a lookup to User :   Agreement_CSH_to_be_completed_by__r  Here is the code which is giving me problems :   public void doManagedClients() {         addMsg('Starting processing of Managed Clients.');         Integer startSize = CSH_Data.size();          String SOQL = 'Select Id, OwnerId, Owner.UserName, Account__c, RecordTypeId, Name, Agreement_Client_Status_History__c ' +             'From Contract_Terms__c Where ' +             '   ( recordtypeid = \''+ ((String)A_N_Rectype).substring(0,15) + '\' ) and ' +                '   Agreement_Client_Status_History__c = \'Monthly\' ' +             'order by createddate desc nulls first' ; system.debug('#####333#### ');               addMsg(DEBUG,'Managed Query is: ' + SOQL + '\n');         for (Contract_Terms__c a: Database.Query(SOQL)) {             if (!a.Agreement_CSH_to_be_completed_by__r.isActive) {                 totalInactiveOwners++;                  addMsg('Account: ' + a.Name +  ', has an inactive owner.  Username: ' + a.Agreement_CSH_to_be_completed_by__r.isActive + '.');             } else {                             totalManagedCSHs++;                 addMsg(DEBUG,'Creating a Managed CSH for Account: ' + a);                 CSH_Data.add(new CSH_and_Share_Pair(a, createClientStatusHistory(a)));                 needflush(false);                 if (error) break;             }         }         needflush(true);         addMsg('End of Managed Clients.');           }   Is it just because I don't have a.Agreement_CSH_to_be_completed_by__r included in the SOQL ? I thought I got different errors for that, so I'm a little confused.  Thank you for your help.
86786
I have a problem with my trigger. In Sandbox, everything works fine. When I deploy it to production, I receive multiple exceptions - which is really strange, because I got angry and put the whole code in &quot;try&quot; block. When I put everything in &quot;try&quot; block, it shouldn't be possible not to catch an exception! This is how my code looks: trigger UpdateLeadField on Lead (before insert, before update) {      //debugging in progress     try{         if(Trigger.New[0].SomeField__c==NULL)         {             for(Lead obj: trigger.new)                 obj.SomeField__c = obj.OwnerId;             return;         }              if (Trigger.New[0].OwnerId != Trigger.Old[0].OwnerId)          {             for(Lead obj: trigger.new)             {                 if(Trigger.New[0].SomeField__c==NULL || [SELECT Name FROM UserRole Where Id = :[SELECT Id, UserRoleId FROM User WHERE Id = :obj.OwnerId][0].UserRoleId].Name == 'Some role')                 obj.SomeField__c = obj.OwnerId;             }         }     }     catch (Exception e)     {         System.debug(e);     } }  The main problem seems to be with Web-to-Lead - When deployed, it stops working. The exception:  Apex script unhandled trigger exception by user/organization: 005C00000XXXXXX/00XXXXX0000LXXQ UpdateLeadField: data changed by trigger for field Some field: id value of incorrect type: 00GC00000XXXXXqMAC  &quot;Some field&quot; is a lookup field.
61579
We are creating custom IDs for Accounts by incrementing an integer field in a custom class. The issue is that if two or more new Accounts are created in close sequence/simultaneously the following code will assign duplicated numbers rather than an incremented number for each:  public static void SetCustomId(Account account) {            CustomObj__c customObj = CustomObj__c.getOrgDefaults();      account.CustomAccountId__c = String.valueOf(Integer.valueOf(customObj.CustomCounter__c));     customObj.CustomCounter__c = customObj.CustomCounter__c + 1;      update customObj; }   Is there a way in Apex to lock a process so that a shared resource is used sequentially? In Java, C#, C++ etc. this is pretty easily done via a critical section if it's a single process or a Mutex if multiple processes access the same resource. Is there anything like this supported in Salesforce? Solutions beside Apex code/triggers would be fine as long as they meet the spec.   EDIT:  It is important that the object creates be sequential and not generate errors due to lockouts.
12761
I am using a similar format for a trigger and helper class.  Can anyone help me with a test class? Trigger Trigger TestOrders on Order (Before Insert)  {     IF(Trigger.IsBefore)     {         IF(Trigger.IsInsert)         {             OrderTriggerHelper.UpdateAccount(Trigger.New);         }     } }    Trigger Class Public Class OrderTriggerHelper {     Public Static Void UpdateAccount(List&lt;Order&gt; OrderIds)     {         List&lt;Account&gt; AccList = [Select Id,Ship_To_Code__c from Account where Ship_To_Code__c != NULL];          IF(AccList != NULL)         {             FOR(Account A : AccList)             {                 FOR(Order O : OrderIds)                 {                     //To check the Case-sensitivity.                     String S1 = A.Ship_To_Code__c;                     String S2 = O.Ship_to_code_del__c;                     IF(S1.Equals(S2))                     {                         O.SFDC_Account_Name__c = A.Id;                     }                 }             }         }     } }
27226
Once a lead is converted it automatically creates an account, contact and one opportunity. But in my case i want to display the result without creating an Account. Please provide me with a sample code.  Any help will be appreciated...
27765
I've been trying to leverage custom roll up functionality and found that Database methods is perfoming dml twice. First time it's inserting/updating all records and second time only ones that can be processed. Is it correct? I'm afraid that I'm missing important part in documentation     The optional allOrNone parameter specifies whether the operation allows partial success. If you specify false for this parameter and a record fails, the remainder of the DML operation can still succeed. This method returns a result object that can be used to verify which records succeeded, which failed, and why.   Since I've placed static boolean to check if trigger has been run, I'm loosing data.  If we create test based on the following    @isTest public class Test_accountTrigger {     @isTest     static void Test_saveResult() {         Account[] accts = new List&lt;Account&gt;{             new Account(Name='Account1'),             new Account()};         Database.SaveResult[] srList = Database.insert(accts, false);     } }   Given trigger will be executed twice  trigger accountTrigger on Account (before insert) {     system.debug('accountTrigger.sise: ' + trigger.new.size()); }   Debug  22:25:31.1 (362723328)|USER_DEBUG|[2]|DEBUG|accountTrigger.sise: 2 22:25:31.1 (498071498)|USER_DEBUG|[2]|DEBUG|accountTrigger.sise: 1   I'm trying to update multiple child records within ETL and inside Salesforce update correspondent Parent records with flag allOrNone set to false. If any of those fails I'm adding error to child record. Since I have static boolean check, my first attempt of updating parent records is reverted and second is never happened.
20439
I am trying to get this trigger to work but it is giving me an error and I am not able to figure out why. The error I am getting is "attempt to de-reference a null object)  Why trigger? We have a Destinations object which is linked to Supplier products object via a lookup relationship. There are two types of supplier products(marketplace and curated) We want to count the number of live Supplier products and put them in a separate fields(live counts for each type).  I have gotten so far to actually count the number of live products and it is giving me an error. Can any one help? I am posting the code below  Trigger code :   trigger NoOfLiveProducts on Supplier_Product__c (after insert, after Delete, after update, after undelete) {       set&lt;string&gt; destinationids = new set&lt;string&gt;();      if(trigger.isInsert) {         for(Supplier_product__c products : Trigger.new) {             destinationids.add(products.Destination__c);         }     } else if(trigger.isDelete) {         for(Supplier_product__c products : Trigger.old) {             destinationids.add(products.Destination__c);         }     }else if(trigger.isUnDelete) {         for(Supplier_product__c products : Trigger.new){             destinationids.add(products.Destination__c);         }      } else if(trigger.isUpdate) {         for(Supplier_product__c products : Trigger.new) {             destinationids.add(products.Destination__c);         }     }      if(destinationids.size() &gt; 0){         Productcounter pc = new Productcounter();         pc.updateproductCount(destinationids);     }    }   Class code :  public class Productcounter {      public void updateproductcount(set&lt;string&gt; productIDs) {           if(productIDs == null){                return;         }          if(productIDs.size() == 0){             return;         }           list&lt;Supplier_Product__c&gt; ProductList = new list&lt;Supplier_Product__c&gt;();         ProductList = [Select ID,Destination__c                     From Supplier_Product__c                     Where Destination__c = :productIDs];          integer totalCount;         map&lt;string, integer&gt; DestinationIDToProductCountMap = new map&lt;string, integer&gt;();                for(Supplier_product__c ProductItem : ProductList){             if(DestinationIDToProductCountMap.containsKey(ProductItem.Destination__c)){                 totalCount = DestinationIDToProductCountMap.get(ProductItem.Destination__c);             }else{                 totalCount = 0;             }             totalCount += 1;             DestinationIDToProductCountMap.put(ProductItem.Destination__c, totalCount);         }          list&lt;Destination__c&gt; DestinationUpdateList = new list&lt;Destination__c&gt;();         Destination__c DestinationTemp;         for(string ProductID : DestinationIDToProductCountMap.keySet()){             DestinationTemp.ID = ProductID;             DestinationTemp.No_of_Live_Curated_Products__c = DestinationIDToProductCountMap.get(ProductID);             DestinationUpdateList.add(DestinationTemp);         }         if(DestinationUpdateList.size() &gt; 0){             update DestinationUpdateList;         }           }           }
85058
I am not able to sum all the opportunities under the account ?  How will I do that?  What I have to use in this to run the trigger? Is it possible to create because opp. is child and account is parent ?  trigger sumAllopptyAmtAccount on Account(before insert) {     Set &lt; ID &gt; AccID = New Set &lt; ID &gt; ();     if (Trigger.isInsert)         for (Account oppAc: trigger.New) {             AccID.add(oppAc.AccountID);         }     List &lt; Account &gt; acc = [select id, SumAll_Opprty__c from Account where id in: a.AccID];     List &lt; Opportunity &gt; opp = [selece id from Opportunity where AccountID in: a.AccID];     for (Account a: acc) {         a.SumAll_Opprty__c = con.size();     } }
114740
I have an existing trigger which converts leads into peron accounts if the company name is blank.  Trigger AutoConvert on Lead (after insert) {      LeadStatus convertStatus = [           select MasterLabel           from LeadStatus           where IsConverted = true           limit 1      ];      List&lt;Database.LeadConvert&gt; leadConverts = new List&lt;Database.LeadConvert&gt;();       for (Lead lead: Trigger.new) {           if (!lead.isConverted &amp;&amp; lead.Company == null) {                Database.LeadConvert lc = new Database.LeadConvert();                String oppName = lead.Name;                 lc.setLeadId(lead.Id);                lc.setDoNotCreateOpportunity(true);                lc.setConvertedStatus(convertStatus.MasterLabel);                 leadConverts.add(lc);           }      }       if (!leadConverts.isEmpty()) {           List&lt;Database.LeadConvertResult&gt; lcr = Database.convertLead(leadConverts);      } }   I need to also write a trigger that stops records from coming into Salesforce if that email already exisits in a contact or an account (we use person accounts).  The issue is how do I get it working with the existing trigger (I need it to run before the trigger that converts it into a person account is run).   Is there a way to combine the two or add the functionality to create the record only if the email address doesn't already exist as a contact in the org?
49131
I'm playing with a trigger exercise, that consists of creating a trigger to create 10 Opportunities whenever a account with more than 100 employees are created. I made the following: trigger AccountTrigger on Account (after insert) {     List&lt;Contact&gt; Contacts = new List&lt;Contact&gt;();     for (Account acct : Trigger.new){                for(integer i = 0; i &lt; 2; i++){             Contact cont    = new Contact();             cont.LastName   = acct.Name+ i;             cont.AccountId  = acct.Id;             Contacts.add(cont);         }         insert Contacts;      if (acct.NumberOfEmployees &gt; 99){         List&lt;Opportunity&gt; Opportunities = new List&lt;Opportunity&gt;();         for(integer i = 0; i &lt; 10; i++){             Opportunity opp = new Opportunity();             opp.Name        = acct.Name + i;             opp.CloseDate   = system.today()+ 30;             opp.StageName   = 'Open';             opp.AccountId   = acct.Id;             Opportunities.add(opp);         }         insert Opportunities;     }                      }  }   And I'm getting the following error: execution of AfterInsert caused by: System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATES_DETECTED, Use one of these records?:  I didn't created any, or changed the dupe rule of account neither Opportuinities. Can you help me understand what kind of error is this? And how can I change the trigger to workaround it? Thanks in advance!!
82116
Since I started coding in Apex, I've gotten used to working with lists of IDs of objects not the objects themselves.  This time around, instead of creating a List&lt;ID&gt; of account ids, I created a List&lt;Account&gt;.  Now, I'm trying to add account records to this list, via a lookup field on a related custom object. However, when I do this, I get an error back telling me I'm trying to add an ID to an sObject list.   So what I'm wondering is, how would I best indicate that it's the sObject record as a whole I want to add, not just the ID indicated by the lookup field? And if it involves a SOQL query, wouldn't that be problematic in terms of hitting governors limits?
90062
I have Opportunity-lookup field on Opportunity (self),  Scenario:   Opportunity A if select Opportunity B using lookup then Opportunity B's same lookup field automatically populate with Opportunity A.   I tried to achieve this using trigger - before insert/update but its failing as:  System.DmlException: Update failed. First exception on row 0 with id 006G000000DHaBlIAL; first error: SELF_REFERENCE_FROM_TRIGGER, Object (id = 006G000000DHaBl) is currently in trigger Oppy_before_INSUPD, therefore it cannot recursively update itself: []
120553
I am creating a cross-objects trigger that whenever a new opportunity is opened, the trigger goes to check whether the company has sold the same product to the customer before; if so, the type of the opportunity will be 'Existing', otherwise it will be 'New'.  trigger InOfficeOp on Opportunity (after insert, after update) {      Set&lt;Id&gt; account_id = new Set&lt;Id&gt;();     List&lt;Id&gt; opp_id = new List&lt;Id&gt;();     for (Opportunity opp: Trigger.new){         if(opp.HasOpportunityLineItem){                         account_id.add(opp.AccountId);             opp_id.add(opp.Id);         }      }       Map&lt;Id, List&lt;Asset&gt;&gt; acc_asset_map = new Map&lt;Id, List&lt;Asset&gt;&gt;();     Map&lt;Id, List&lt;OpportunityLineItem&gt;&gt; opp_prod_map = new Map&lt;Id, List&lt;OpportunityLineItem&gt;&gt;();      for(Asset ast: [SELECT  Product2Id, AccountId FROM Asset WHERE AccountId IN: account_id]) {         if(acc_asset_map!=null &amp;&amp; acc_asset_map.containsKey(ast.Product2Id)) {             List&lt;Asset&gt; asset_List = acc_asset_map.get(ast.Product2Id);             asset_List.add(ast);             acc_asset_map.put(ast.Product2Id,asset_List);         }         else {             acc_asset_map.put(ast.Product2Id, new List&lt;Asset&gt;{ast});             }     }      for (OpportunityLineItem oli: [SELECT Product2Id, OpportunityId FROM OpportunityLineItem WHERE OpportunityId IN: opp_id]){         if(opp_prod_map!=null &amp;&amp; opp_prod_map.containsKey(oli.Product2Id)){             List&lt;OpportunityLineItem&gt; oppLineItem_Recd = opp_prod_map.get(oli.Product2Id);             oppLineItem_Recd.add(oli);             opp_prod_map.put(oli.Product2Id, oppLineItem_Recd);                 }         else {             opp_prod_map.put(oli.Product2Id, new List&lt;OpportunityLineItem&gt;{oli});          }     }     Id op;     for(Id prodId: acc_asset_map.keyset()){         if(opp_prod_map!= null &amp;&amp; opp_prod_map.containsKey(prodId)) {             for(OpportunityLineItem oppLine_Recd:opp_prod_map.get(prodId)) {                 op = oppLine_Recd.OpportunityId;             }         }     }     for(Opportunity o:Trigger.new){         if(o.Id == op){             o.Type = 'Existing_Business';         }         else{             o.Type = 'New_Business';         }     }     }   The above is my trigger code.  And here is my test:  @isTest private class OppTriggerTest{     static void PopulateExtensiontest()      {         Date closeDt = Date.Today();         date myDate = date.today();          Account a2 = new Account(Name='icrm test acc');         insert a2;          Opportunity oppr = new Opportunity(Name='testing DIE 6/4/2017', AccountId = a2.Id,StageName='Prodpecting',  CloseDate = Date.Today());         insert oppr;          Pricebook2 pb22 = new Pricebook2(Name='testDIE');         insert pb22;          Product2 pro2 = new Product2(Name='BXCD', isActive=true);         insert pro2;          PricebookEntry pbe2 =new  PricebookEntry(unitprice=0.01,Product2Id=pro2.Id, Pricebook2Id=Test.getStandardPricebookId(), isActive=true, UseStandardPrice=false);          insert pbe2;          OpportunityLineItem OPplineitem2 = new OpportunityLineItem (Quantity=2, OpportunityId=oppr.Id, UnitPrice=0.01, PriceBookEntryId =pbe2.Id);         insert OPplineitem2;          update oppr;     } }   And I got the error message after I exceture the test:     System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, InOfficeOp: execution of AfterInsert caused by: System.FinalException: Record is read-only   Trigger.InOfficeOp: line 51, column 1: []   I don't quite understand what does the message mean. Could anyone please help me what does the error mean? Is my test wrong?