Please help me to write a test class for the below code trigger RelatedRecord on Account(after insert, after update) {    List&lt;opportunity&gt; opportunityList = new List&lt;opportunity&gt;();    Map&lt;Id,Account&gt; accountswithopp = new Map&lt;Id,Account&gt;();    ([select Id,(select Id from opportunities) from Account Where Id IN :Trigger.New]);    for(Account acc : Trigger.New) {       System.debug('accountswithopp.get(acc.Id).opportunities.size()=' + accountsWithopp.get(acc.Id).opportunities.size());       if (accountswithopp.get(acc.Id).opportunities.size() = 0) {          opportunityList.add(new Opportunity(                      Name=acc.Name + ' opportunity',                        StageName='Prospecting',                        CloseDate=System.today().addMonths(3),                        AccountId=acc.Id));       }    }    if (opportunityList.size() &gt; 0) {       insert opportunityList;    } }
5058
This is a canonical question and answer developed by the community to help address common questions. If you've been directed here, or your question has been closed as a duplicate, please look through the resources here and use them to shape more specific questions. To browse all canonical questions and answers, including more unit test resources, navigate to the  tag.  This canonical question is intended to address several classes of common questions by providing a quick summary and links to comprehensive resources:   How do I start writing my first unit test?  How do I unit test this code?  I need help writing this unit test.   Salesforce Stack Exchange looks for detailed, specific questions that the community can help you with, and can't write tests on your behalf. We feel that working with the resources below can help you get started, and we encourage you to make an attempt to write your test and return to SFSE with your specific questions when you encounter challenges you can't resolve.
123622
How how do I query recent account views and group by LastViewedDate    SELECT Id, Name                 FROM Account                ORDER BY Name DESC limit 10 FOR VIEW   I used to have it like this, but my test case is keep failing  SELECT SELECT Id, Name, LastModifiedDate                         FROM account                         WHERE LastModifiedDate !=null ORDER BY LastViewedDate DESC limit 10  static testmethod void testOppExt_TestMethod(){        Opportunity testOpp = new Opportunity(Name = 'TestOpp', StageName='Test', CloseDate = Date.today());       insert testOpp;        Account testAcc = new Account(Name = 'Test Account');       insert testAcc;        Contact con = new Contact(LastName='Test',AccountId=testAcc.id);       insert con;        Test.startTest();       OppExt testCon = new OppExt();       Contact conn = testCon.contact;       Account  Accn = testCon.acc;       Test.stopTest();     }   Error Message   Component Errors API Name Type Line Column Error Message 0 0 , Details: Average test coverage across all Apex Classes and Triggers is 0%, at least 75% test coverage is required. 0 0 SiteRegisterControllerTest.null(), Details: line -1, column -1: Previous load of class failed: oppext null 0 0 SiteLoginControllerTest.null(), Details: line -1, column -1: Previous load of class failed: oppext null 0 0 SiteRegisterController.null(), Details: line -1, column -1: Previous load of class failed: oppext null 0 0 testnewOpportunityController.null(), Details: line -1, column -1: Previous load of class failed: oppext null 0 0 SiteLoginController.null(), Details: line -1, column -1: Previous load of class failed: oppext null 0 0 testOppExt.null(), Details: line -1, column -1: Previous load of class failed: oppext null 0 0 OppExt.null(), Details: line 32, column 17: No such column 'LastViewedDate' on entity 'Account'. If you are attempting to use a custom field, be sure to append the '__c' after the custom field name. Please reference your WSDL or the describe call for the appropriate names. null
44999
I am trying to write a test class for the Apex Class with try - catch block and this is my first time coding test classes. The Apex Class is like below which has trycatch   public class updateCaseRecord {          @AuraEnabled     public static void updateCheck(String caseId){         String msg = '';         try         {         List&lt;Case&gt; records = [select id,Status from Case WHERE Id = :caseId];         for (Case record : records)         {             record.Status = 'Closed';         }         update records;          }         catch(DmlException e)              {                for (Integer i = 0; i &lt; e.getNumDml(); i++) {                     msg =+ e.getDmlMessage(i) +  '\n' ;                     System.debug('getDmlFieldNames=' + e.getDmlFieldNames(i));                    System.debug('getDmlMessage=' + e.getDmlMessage(i));                   }                 throw new AuraHandledException(msg);             }             catch(Exception e)             {             throw new AuraHandledException(e.getMessage());             }             finally { }           }}   And I wrote my test class like   @IsTest public class updateCaseRecordTest { @IsTest static void testIsUpdateCheck() {      ID parentRecType = '012U0000000PqA9IAK';     ID csRecType     = '012U0000000QGv4IAG';       Account pa = new Account(Name='Test Parent Account', recordTypeId=parentRecType);     insert pa;      Account testAccount = new Account(Name='test', Industry='Biotech',Territory__c='EUR',BillingCity='Test',BillingCountry='Germany',ParentId=pa.id);     insert testAccount;       Contact c = new Contact(LastName='Test',LeadSource='Customer Service',AccountId=testAccount.Id);     insert c;      Case newCase1 = new Case();     newCase1.Subject = 'testStatusClosed';     newCase1.Status = 'New';     newCase1.Category__c = 'Inquiry';     newCase1.Sub_Category__c = 'Other';     newCase1.AccountId = testAccount.Id;     newCase1.ContactId = c.id;     newCase1.recordTypeId=csRecType;     insert newCase1;       Test.startTest(); try     {     updateCaseRecord.updateCheck(newCase1.Id);     List&lt;Case&gt; lCases = [SELECT Id,Status,OwnerId FROM Case WHERE Id =: newCase1.Id];     System.assertEquals('Closed', lCases[0].Status);      System.assertEquals(UserInfo.getUserId(), lCases[0].OwnerId);     }      catch(DMLException e) {         System.assertEquals(e.getMessage(), e.getMessage());     }      Test.stopTest();    }}   I thought I captured the try catch but when I run the test class it has only 57% code coverage and shows like below    Following one of the answers here
101111
We've had a community deployment and my brain is fried and I just whipped up a quick class that is throwing the below error. What have I done wrong here?     Error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, MSI_UserTrigger:   execution of AfterInsert caused by: System.StringException: Invalid   id: () : [] () : []: ()   What I am trying to accomplish is:   When a new user is created and is active, if they are linked to a ContactId and part of a specific profile (by name), add their ContactId to a Set&lt;ID> Then loop through contacts where the Id is in the set, and update the Community_User__c field to TRUE      Trigger:   trigger MSI_UserTrigger on User (after insert) {       if(Trigger.isAfter){          if(Trigger.isInsert){              MSIUserTriggerHandler.executeAfterInsert(Trigger.new);          }      } }      Class:   public with sharing class MSIUserTriggerHandler {     private static final String COMMUNITY_PROFILE = 'Community Knowledge User';     private MSIUserTriggerHandler() {}      public static void executeAfterInsert(List&lt;User&gt; newList){         setCreatedCommunityUsers(newList);     }      private static void setCreatedCommunityUsers(List&lt;User&gt; newList){         List&lt;User&gt; usersWithContacts = new List&lt;User&gt;();         List&lt;Contact&gt; contactsToUpdate = new List&lt;Contact&gt;();         Set&lt;ID&gt; contactIds = new Set&lt;ID&gt;();          for(User u: newList){             if(u.ContactId == null &amp;&amp; u.ContactId == ''){                 continue;             }             if((u.ContactId != null &amp;&amp; u.ContactId != '') &amp;&amp; u.Profile.Name == COMMUNITY_PROFILE &amp;&amp; u.isActive == true){                 contactIds.add(u.ContactId);             }         }          for(Contact c : [Select Id,Name,Community_User_Created__c from Contact where Id in :contactIds]){             if(!c.Community_User_Created__c){                 c.Community_User_Created__c = true;                 contactsToUpdate.add(c);             }         }         update contactsToUpdate;     } }   Am I not adding the ID correctly to the Set&lt;ID>, or am I querying wrong in my for(Contacts) loop?
105631
Please consider the below scenario:   I have an Application__c object. I have a trigger on that (for simplicity, coded directly in trigger) which does one thing if the record name is Error then throws exception.     trigger ApplicationTrigger on Application__c (before insert, after update){          if(trigger.new[0].Name == 'Error'){             Application__c application;             System.debug(application.Name);         } }    Now I am running below code:     Now notice the catch statement is not executing, means system was not able to catch the exception. It came as the Fatal Error.   This is kind of a big issue where if there is null pointer or any other exception in trigger and exception handling code will not be able to do anything. Not even logging since it never reaches to catch block.   Let me know if you guys ever faced such situation and if yes what you did to make sure that it is properly caught.
56738
In Field Service Lightning I have a Trigger on ServiceReport which sends an email with attachment coming from ContentVersion.   This is the Test class I have written.  @isTest  private class testCreateServiceReport{       static testMethod void validateWO() {       WorkOrder wo = new WorkOrder();       wo.subject = 'Testing';       insert wo;       ServiceAppointment sa = new ServiceAppointment();       sa.ParentRecordId = wo.Id;       sa.EarliestStartTime = DateTime.now();       sa.DueDate = DateTime.now();       insert sa;       List&lt;ServiceReportLayout&gt; srl = [Select Id FROM ServiceReportLayout];       ServiceReport sr = new ServiceReport();       sr.ParentId = sa.Id;       sr.Template = srl[0].Id; //Need to check if there is a way to avoid srl[0] notation       insert sr; //If I comment this the text result is pass. When I enable it I get too see the below mentioned error.  }  }   This is the error Methods defined as TestMethod do not support Web service callouts I know that we need to write Test Classes for code that involves web service callouts using setMock() but I dont understand in what way inserting ServiceReport is related to making a callout.  Any help on this will be really helpful.
96142
I am working on a requirement to create an opportunity and opportunity products , when there is an update on the asset object.  The asset object has a filed called Refresh_Asset_To__c, this is a lookup to the product object.   Basically each time I change the product on the Refresh_Asset_To__c, a new opportunity should be generated with the Refresh_Asset_To__c being the opportunity product.  I have tested , and its generating the opportunity , but each time i try to insert the opportunity product I get the error :      Update failed. First exception on row 0 with id 02i3B000003TAk7QAG; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, AssetRefreshOpp: execution of AfterUpdate caused by: System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, field integrity exception: PricebookEntryId (pricebook entry currency code does not match opportunity currency code): [PricebookEntryId] Trigger.AssetRefreshOpp: line 56, column 1: []   This is my code:  trigger AssetRefreshOpp on Asset (after update) {      Pricebook2 ikmBook    = [SELECT Id,CurrencyIsoCode FROM Pricebook2 WHERE Id = '01s46000003K1zXAAS'];  List&lt;OpportunityLineItem&gt; oppLiList = new List&lt;OpportunityLineItem&gt;(); Opportunity opp; OpportunityLineItem oli; string refeshed;     List&lt;asset&gt; refreshedAss = [select Id,Contract__r.EndDate,OwnerId,quantity,Name,Refresh_Asset_To__c,Refresh_Asset_To__r.Id,AccountId,account.name from asset                                      where Id IN : Trigger.new                                      And Refresh_Asset__c = True];          for(asset myAss:refreshedAss){             // Create New Opportunity              Opportunity newopp =new Opportunity();   newopp.Name=myAss.account.name + ' ' + 'refreshed'; newOpp.AccountId = myAss.AccountId; newOpp.CloseDate = myAss.Contract__r.EndDate; newOpp.StageName = 'Create'; newOpp.RecordTypeID = '01246000000TfMZAA0'; newOpp.OwnerId = myAss.OwnerId; newOpp.Amount = 0; newOpp.Type= 'Existing Business'; newOpp.OM_Order_Type__c = 'Regular'; newOpp.CurrencyIsoCode = ikmBook.CurrencyIsoCode; newOpp.Pricebook2Id = ikmBook.Id;  insert newOpp;          List&lt;PriceBookEntry&gt; priceBookList = [SELECT Id, Product2Id,CurrencyIsoCode, Product2.Id, Product2.Name FROM PriceBookEntry WHERE  PriceBook2.isStandard=true LIMIT 1];               for(asset myAssets:refreshedAss){               OpportunityLineItem oli = new OpportunityLineItem();                oli.OpportunityId = newOpp.Id;                oli.Product2Id = myAssets.Refresh_Asset_To__r.Id;                oli.PriceBookEntryId = priceBookList[0].Id;                oli.UnitPrice = 0;               oli.Quantity = myAssets.Quantity;               oppLiList.add(oli);           }           insert oppLiList;               } }
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.
99580
I am new to Salesforce development. I made a trigger that creates a new asset record and autofills some of the fields on said record. What I want ultimately would be a button that I can put on the "Products" related list on the opportunity page that does what my trigger does. From what I understand, I can't just call my trigger on the button click, and I have to create a VF page or an Apex class that uses the trigger's logic. Does anyone know how I would go about doing this? Here's my code:  trigger ConvertOpportunitiesToAssets on Opportunity (after update) {      List&lt;Asset&gt; a = new List&lt;Asset&gt;();     OpportunityLineItem oli = new OpportunityLineItem();      for(Opportunity o: Trigger.new)     {                   a.add( new Asset(             PSI_Supplier__c = o.Supplier__c,             PSI_Opportunity__c = oli.Product2Id,             AccountId = o.Accountid,             Name = oli.Product2Id,             Product2Id = oli.Product2Id,             Product_Name__c = oli.Product_Name__c             ));            }     insert a; }   Thanks in advance!  UPDATE So I tried making the trigger into a class and button (thanks sfdcfox!), but now it won't work. Here's what I've got:      global class OpportunityWS{     webservice static void createAsset(Id opportunityId)     {         List&lt;Asset&gt; a = new List&lt;Asset&gt;();         Opportunity o = new Opportunity();         OpportunityLineItem oli = new OpportunityLineItem();          a.add( new Asset(             PSI_Supplier__c = o.Supplier__c,             PSI_Opportunity__c = oli.Product2Id,             AccountId = o.Accountid,             Name = oli.Product2Id,             Product2Id = oli.Product2Id,             Product_Name__c = oli.Product_Name__c             ));                 insert a;      } }  {!RequireScript("/soap/ajax/34.0/connection.js")} {!RequireScript("/soap/ajax/34.0/apex.js")} function success() { var alertString="Success!";  alert(alertString);  } function error() { var alertString="Error!";  alert(alertString);  } sforce.connection.sessionId = "{!$Api.Session_ID}"; sforce.apex.execute("OpportunityWS", "createAsset", { opportunityId: "{!Opportunity.Id}" }, { onSuccess: success, onFailure: error });   I can't tell if it's something wrong with the class or the button. I think it must be the class.  UPDATE(AGAIN) Alright so I followed Doug's advice and tried to use the opportunityId to query the opportunity and opportunityLineItem sobjects, was able to compile without errors. But now I'm getting the error message that I made in the button thrown and the asset isn't being created. Unfortunately, I haven't been able to track down the issue. Here's the OpportunityWS apex class that I've updated since last edit:  global class OpportunityWS{ webservice static void createAsset(Id opportunityId) {     List&lt;Asset&gt; a = new List&lt;Asset&gt;();     List&lt;Opportunity&gt; o = [SELECT Supplier__c, Accountid FROM Opportunity WHERE Id = :opportunityId];     List&lt;OpportunityLineItem&gt; oli = [SELECT Product2Id, Product_Name__c FROM OpportunityLineItem WHERE Id = :opportunityId];      a.add( new Asset(         PSI_Supplier__c = o[0].Supplier__c,         PSI_Opportunity__c = oli[0].Product2Id,         AccountId = o[1].Accountid,         Name = oli[0].Product2Id,         Product2Id = oli[0].Product2Id,         Product_Name__c = oli[1].Product_Name__c         ));             insert a; }   }
4667
Getting error with this code but I can't figure it out  trigger LeadConvert on Lead (after insert) {     list leadsToConvert = new list();      Database.LeadConvert lc;     string convertedStatus = '';     list convertStatusList = new list();     convertStatusList = [Select Id, MasterLabel                          from LeadStatus where IsConverted=true limit 1];     if(convertStatusList.size() &gt; 0){         convertedStatus = convertStatusList[0].MasterLabel;         }     else{              convertedStatus = 'Closed - Converted';          }      for(Lead l : trigger.New){         if(l.AutoConvert__c == true){             lc = new database.LeadConvert();             lc.setLeadId(l.ID);             lc.setDoNotCreateOpportunity(true);              lc.setConvertedStatus(convertedStatus);             leadsToConvert.add(lc);         }     }      list lcrList = new list();     lcrList = Database.convertLead(leadsToConvert); }
68198
I do have a requirement like I need to write a trigger on user object.The trigger must be before update, which should give the value of previous and current profile assigend to a user.  any help??  This is what I have done, but not getting anything in debug log  trigger UserProfileTrigger on User (before update) {  for(Integer i = 0; i&lt; Trigger.new.size(); i++) {         if(Trigger.new[i].Profile!= Trigger.old[i].Profile){          System.debug('***SFDC: Trigger.old is: ' + Trigger.old[i].profile);          System.debug('***SFDC: Trigger.new is: ' + Trigger.new[i].profile);           }     } }
42790
I am writing a trigger to get all the Opportunity competitors into a field on Opportunity, however, getting an error while testing it.  Error: updateCompetitors: execution of AfterUpdate caused by: System.FinalException: Record is read-only: Trigger.updateCompetitors: line 24  Can you please check the below code and suggest me what's wrong with this?  trigger updateCompetitors on Opportunity(after insert, after update){    List&lt;Opportunity&gt; OppIds = new List&lt;Opportunity&gt;();     for (Opportunity opp: trigger.new){         OppIds.add(opp);     }  List&lt;OpportunityCompetitor&gt; oppComps = new List&lt;OpportunityCompetitor&gt;();  oppComps= [select id, CompetitorName, Strengths, Weaknesses from OpportunityCompetitor where OpportunityId in: Trigger.newMap.keySet()];  List&lt;Opportunity&gt; OppstoUpdate = new List&lt;Opportunity&gt;();   for (Opportunity opp: OppIds){     String allcomps = null;      if( oppComps.size()&gt;0 ) {       for (integer i = 0; i &lt; oppComps.size(); i++){          allcomps = allcomps + oppComps[i].CompetitorName+',';       }     }    opp.OpportunityCompetitors__c = allcomps;    OppstoUpdate.add(opp);  }    update OppstoUpdate; }
72265
trigger VINfromAccountandContact on Case (before insert) {     Set&lt;id&gt; setConids = new Set&lt;id&gt;();     Map&lt;id,id&gt; mapAccidVsVIN = new Map&lt;id,id&gt;();     for(Case c:trigger.new){         if(c.Contactid &lt;&gt; NULL){             setConids.add(c.Contactid);          }     }     if(!setConids.isEmpty()){         for(Contact_Vehicle_Ownership__c cv :[SELECT id,Account_Name__c,Contact_Name__c,VIN_Lookup__r.id FROM Contact_Vehicle_Ownership__c WHERE Contact_Name__c IN:setConids]){             mapAccidVsVIN.put(cv.Contact_Name__c, cv.VIN_Lookup__r.id);         }     }      for(Case c:trigger.new){         if(mapAccidVsVIN.containsKey(c.Contactid)){             c.VIN__c = mapaccidVsVIN.get(c.Contactid);         }     } }   I want to add this condition when accountid is not equal to Null can any one help how do i add this condition
74793
I have written a method which I will call in a Trigger.While trying to save this code as Apex class, I am getting the error " Error: Compile Error: Loop variable must be of type SObject at line 7 column 13"   My code goes as below ,appreciate any help, thanks  public class LeadBefore {     public static void UpdateChapterEmailAddress (){          set&lt;Id&gt; JDRFLocationId = new set&lt;Id&gt;();         List&lt;Lead&gt; vLstLead = new List&lt;Lead&gt;();           for(Lead vLead:trigger.new)         {             if(vLead.JDRF_Location__c != null)             {                 JDRFLocationId.add(vLead.JDRF_Location__c);                 vLstLead.add(vLead);             }         }         Map&lt;Id, JDRF_Location__c&gt; vMapIdJDRFLocat = new Map&lt;Id, JDRF_Location__c&gt;([Select Id, Name, General_Email_Address__c from JDRF_Location__c where Id In: JDRFLocationId]);         for(Lead vLead: vLstLead)         {             if(vMapIdJDRFLocat.containsKey(vLead.JDRF_Location__c))             {                 vLead.Chapter_Email_Address__c = vMapIdJDRFLocat.get(vLead.JDRF_Location__c).General_Email_Address__c;             }         }     } }
32544
I’m in a situation where I have to use a future method to avoid  MIXED_DML_OPERATION error. I have a trigger that runs after INSERT on USER and creates  a custom object X. They are in 1:1 relation. User is an owner of X and sharing model is private.  I’m not sure what is the best approach to write tests for this scenario.  I want to keep my data isolated so in tests I need to create a User and X he owns. I can think of 2 scenarios:  1)  Create a mock user and let the trigger create X for the test  Because in test context @future methods are executed  when the Test.stopTest() is called I would have to enclose my set up section in Test.start/stopTest(). This means I can’t use these two later in the method where I want to  test a particular logic on X.   2)  Create a mock user, don't wait for future method and create X manually in mock section  I can write a single test  for creation of X in the trigger. In all other  tests checking  the business logic  on X I create a user, manually create X setting the user as the owner. The problem is that now if later in the method I call Test.start/stopTest() and do a select from X where ownerId = user.id I will get two X records.  To my surprise I discovered that I’m able to insert X objects from the trigger while running a test. I didn't use the @future method and I got no MIXED_DML_OPERATION error ( - a bug?).  for(User aUser: newUsers){       newXtoInsertFromFuture.put(aUser.ID, aUser.lastName )       objectX.add(new X(ownerID=aUser.id, property=aUser.lastName));  } if(Test.isRunningTest()){         insert objectX; }else{         matchUsersWithX(newXtoInsertFromFuture); }  With this code in trigger I can create a user in a test set up section and the corresponding X is created synchronously. I’m not sure why things work this way.  Anyway this looks like a dirty hack that yields the same problems as 2) if I ever call Test.start/stopTest() in the test.  Could any of you good people out there tell me what is the correct way to write tests in my case? thanks in advance.
78811
I added a new field on Opportunity table to keep a count of records, as well as track the updates made on that record.  This is needed for an external system we use. Opportinity table already has around 5000 records now. I would like to update the new field that I added with some sequence order initially. Say each record to have a unique sequence number like 1,2,3 etc(can't use the Id field for unique). The field "Identifier__c" was added for this purpose with data type number and unique contraint. For that I created a temporary class and trigger. But it is throwing the error.     Review all error messages below to correct your data. Apex trigger OpportunitySAPIdentifierHandler caused an unexpected exception,   contact your administrator: OpportunitySAPIdentifierHandler: execution   of BeforeUpdate caused by: System.DmlException: Update failed. First   exception on row 0 with id 006E00000038FPSIA2; first error:   CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, OpportunitySAPIdentifierHandler:   execution of BeforeUpdate caused by: System.DmlException: Update   failed. First exception on row 0 with id 006E00000038FPTIA2; first   error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY,   OpportunitySAPIdentifierHandler: execution of BeforeUpdate caused by:   System.DmlException: Update failed. First exception on row 0 with id   006E00000038FPSIA2; first error: SELF_REFERENCE_FROM_TRIGGER, Object   (id = 006E00000038FPS) is currently in trigger   OpportunitySAPIdentifierHandler, therefore it cannot recursively   update itself: [] Class.AutoNumber.OpportunityAutoNumber: line 76,   column 1 Trigger.OpportunitySAPIdentifierHandler: line 4, column 1: []   Class.AutoNumber.OpportunityAutoNumber: line 76, column 1   Trigger.OpportunitySAPIdentifierHandler: line 4, column 1: []:   Class.AutoNumber.OpportunityAutoNumber: line 76, column 1   Below is the trigger and class used.  trigger Opportuniwith sIdentifierHandler on Opportunity (before insert,before update) {          If(Trigger.isInsert || Trigger.isUpdate){             AutoNumber.OpportunityAutoNumber(Trigger.new);         }   }   The class is   public with sharing class AutoNumber {       public static void OpportunityAutoNumber (List&lt;Opportunity&gt; Opp) {          if(Trigger.isUpdate || Trigger.isInsert) {              for(Opportunity p: Opp) {                  List&lt;Opportunity&gt; oppList = new List&lt;Opportunity&gt;();                 oppList = [SELECT Id, createdDate, Identifier__c FROM Opportunity where Identifier__c = null and Id != :p.Id limit 100 FOR update];                 for (Opportunity oppL: oppList) {                      if(oppL.Identifier__c == null) {                          List&lt;Opportunity&gt; OpportunityList = new List&lt;Opportunity&gt;([select Identifier__c from Opportunity where Identifier__c != null order by Identifier__c desc limit 1]);                          if (!OpportunityList.isEmpty()) {                               Decimal maxval = OpportunityList.get(0).Identifier__c;                             oppL.Identifier__c = maxval + 1;                             update oppL;                         }                      }                     // integer currentCounter = Integer.valueOf(opp.Identifier__c);                     // oppr.Identifier__c = currentCounter + 1;                     // update oppr;                 }             }         }        }  }
56910
The function of this apex code is when Account has no Contacts the first contact created become the primary contact and when there is existing primary contact it cannot assign a other primary contact on account. Please help to optimized my code to easy understand.Thanks for the help.  public class CreatePrimaryContactHandler {     public static void createPrimary(List&lt;Contact&gt; contactList)     {        Set&lt;Id&gt; accountId = new Set&lt;Id&gt;();         for(Contact c : contactList)         {             accountId.add(c.AccountId);         }         List&lt;Contact&gt; allContact = [SELECT Id, Account.Id, Primary_Contact__c FROM Contact WHERE (Account.Id IN : accountId)];         Map&lt;Id, List&lt;Contact&gt;&gt; acctContactMap = new Map&lt;Id, List&lt;Contact&gt;&gt;();             for(Id aId : accountId)             {              List&lt;Contact&gt; conList = new List&lt;Contact&gt;();                 for(Contact allcont : allContact)                 {                     if(allcont.AccountId == aId)                     {                     conList.add(allcont);                     }                 }                 acctContactMap.put(aId, conList);             }             for(Id accId : acctContactMap.keySet())             {                 Integer count = 0;                 for(Contact c : contactList)                 {                     if(c.AccountId == accId &amp;&amp; c.Primary_Contact__c)                     {                         count++;                     }                 }                 if(count &lt;= 1)                 {                     List&lt;Contact&gt; cList = acctContactMap.get(accId);                     Contact primary;                     Boolean isPrimary = false;                     for(Contact cont : cList)                     {                         if(cont.Primary_Contact__c)                         {                             isPrimary = true;                         }                     }                     for(Contact cont : contactList)                     {                         if(cont.AccountId == accId)                         {                             if(cont.Primary_Contact__c)                             {                                 if(primary != null)                                 {                                     primary.Primary_Contact__c = false;                                      isPrimary = false;                                 }                                 else if(isPrimary)                                 {                                 cont.addError('Invalid Primary Contact. This Account has already an existing Primary Contact.');                                 }                                     else                                     {                                         cont.Primary_Contact__c = true;                                         isPrimary = true;                                     }                             }                                    else if(!isPrimary)                                 {                                     cont.Primary_Contact__c = true;                                     isPrimary = true;                                     primary = cont;                                 }                         }                     }                 }                 else                 {                     contactList.get(0).addError('Invalid Primary Contact. This Account has already an existing Primary Contact.');                 }         }       } }   This is the Trigger  trigger CheckPrimaryContact on Contact (before insert,after update,before update){     if(trigger.IsInsert &amp;&amp; trigger.IsBefore){         CreatePrimaryContactHandler.createPrimary(trigger.new);     }     if(trigger.IsBefore &amp;&amp; trigger.IsUpdate){         CreatePrimaryContactHandler.createPrimary(trigger.new);     } }