public static void insertLogicHandler(List&lt;Task&gt; listNewTasks, Map&lt;Id, Task&gt; mapNewTasks, String context){         List&lt;Task&gt; listTasks = mapNewTasks.values();         Map&lt;Id, Task&gt; mapFlowTasks = new Map&lt;Id, Task&gt;();          //business logic to create sub-Maps that are passed into specific methods         for(Task t: listTasks){             System.debug('#### in TaskTrigger_Handler.insertLogicHandler for loop');             if(t.WhoId != null &amp;&amp; t.Type != 'Campaign Email'){                 mapFlowTasks.put(t.Id, t);//This line is not covering              } }   I have created the task dummy records ,while assigning who id as contact.id,I'm encountering flow exception.Could anyone help me with covering the Map?
3698
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 is code coverage obtained and calculated? How do I increase my coverage?  Why can't I cover these lines? Why isn't the body of my loop or conditional statement covered?
110175
I am receiving an error stated above on line 26**(listAccount1)**, can anyone guide me on how to solve it?  public class FRB_UpdateExceptionsforBatch {    public static void FRB_Exceptions(){    string FRBRecordTypeID = utility.getFRBProfileNameLabel();       List&lt;Account&gt; lstAccount = new List&lt;Account&gt;();         List&lt;Account&gt; lstAccount1 = new List&lt;Account&gt;();         List&lt;Account&gt; lstAccount2 = new List&lt;Account&gt;();         List&lt;Account&gt; lstAccount3 = new List&lt;Account&gt;();    lstAccount = [Select id,FRB_Firm_Check__c,Number_of_Exception__c,Number_of_exceptions_under_4_6_bucket__c,Number_of_exceptions_under_7_10_bucket__c,Number_of_exceptions_under_11_19_bucket__c,(select id,Account_Standing__c from Process_Adherence_Monitoring__r  where Status__C != 'Closed' AND  recordtypeId =: FRBRecordTypeID AND Account_Standing__c = '0-3 Days (Green - New Exception)' ) FROM Account WHERE FRB_Firm_Check__c = TRUE];     if(lstAccount.size()&gt;0){           for( Account acc : lstAccount )           {               List&lt;Process_Adherence_Monitoring__c&gt; lstCont = acc.Process_Adherence_Monitoring__r;                acc.Number_of_Exception__c = lstCont.size();               acc.FRB_Firm_Check__c = true;           }            update lstAccount;     }         //To update 4-6 bucket      lstAccount1 = [select Id, Name,FRB_Firm_Check__c, Number_of_exceptions_under_4_6_bucket__c,(select id,Account_Standing__c from Process_Adherence_Monitoring__r  where Status__C != 'Closed' AND  recordtypeId =: FRBRecordTypeID AND Account_Standing__c = '4-6 Days (Yellow - Outside Correction Timeframe)' ) from Account where FRB_Firm_Check__c = TRUE];        if(lstAccount1.size()&gt;0){           for( Account acc : lstAccount1 )           {               List&lt;Process_Adherence_Monitoring__c&gt; lstCont1 = acc.Process_Adherence_Monitoring__r;                              acc.Number_of_exceptions_under_4_6_bucket__c= lstCont1.size();               acc.FRB_Firm_Check__c = true;           }            update lstAccount1 ;       }         //To update 6-11 bucket         lstAccount2 =  [select Id, Name,FRB_Firm_Check__c, Number_of_exceptions_under_7_10_bucket__c,(select id,Account_Standing__c from Process_Adherence_Monitoring__r  where Status__C != 'Closed' AND  recordtypeId =: FRBRecordTypeID AND Account_Standing__c = '7-10 Days (Orange - Approaching Critical Timeframe)' ) from Account where FRB_Firm_Check__c = TRUE];        if(lstAccount2.size()&gt;0){           for( Account acc : lstAccount2 )           {               List&lt;Process_Adherence_Monitoring__c&gt; lstCont2 = acc.Process_Adherence_Monitoring__r;                acc.Number_of_exceptions_under_7_10_bucket__c= lstCont2.size();               acc.FRB_Firm_Check__c = true;           }           update lstAccount2 ;       }        //To update 11 bucket            lstAccount3 =  [select Id, Name,FRB_Firm_Check__c, Number_of_exceptions_under_11_19_bucket__c,(select id,Account_Standing__c from Process_Adherence_Monitoring__r  where Status__C != 'Closed' AND  recordtypeId =: FRBRecordTypeID AND Account_Standing__c = '11-19 Days (Red - Immediate Correction Required)' ) from Account where FRB_Firm_Check__c = TRUE];        if(lstAccount3.size()&gt;0){           for( Account acc : lstAccount3 )           {               List&lt;Process_Adherence_Monitoring__c&gt; lstCont3 = acc.Process_Adherence_Monitoring__r;                acc.Number_of_exceptions_under_11_19_bucket__c= lstCont3.size();               acc.FRB_Firm_Check__c = true;           }                              update lstAccount3 ;       }      }   }
104197
When i create new User Account and login with that credentials, it gives me this problem if admin doesnt have set thier values yet !!!**  AllotmentList = [select id, Days_Remaining__c from PTO_Allotment__c where Year__c =:year and Employee__c=:EmployeeList[0].id LIMIT 100]; //access only Current user Allotment details                 //to handle Listoutof Bound Exception wrote if-else          if(AllotmentList.size()&gt;0)         {         requests.PTO_Allotment__c=AllotmentList[0].id;         requests.Days_Remaining__c=AllotmentList[0].Days_Remaining__c;         }         else         {             //write a code when AllotmentList is empty ....         }
37684
I'm trying create a Map using a name field as key.  Sample code:  Set&lt;String&gt; priceBooksNames = new Set&lt;String&gt;(); priceBooksNames.add('LN-200'); priceBooksNames.add('LN-100');  Map&lt;string,PriceBook2&gt; priceBooks = new Map&lt;string,PriceBook2&gt;([SELECT name,id FROM PriceBook2 WHERE name=:priceBooksNames ]); system.debug(priceBooks.get('LN-100')); //this is returning NULL   I can see on console that setId on map is not getting the name field value.  VARIABLE_ASSIGNMENT [5]|priceBooks|{"serId":1,"value":{"01sb0000000hiqQAAQ":{"serId":2,"value":{"Name":"LN-100 ADULTOS","Id":"01sb0000000hiqQAAQ"}},"01sb0000000hiqGAAQ":{"serId":3,"value":{"Name":"LN-200 EMPRESAS","Id":"01sb0000000hiqGAAQ"}}}}   What I'm going wrong?
38358
I've been learning C#, and I'm trying to understand lambdas.  In this sample below, it prints out 10 ten times.  class Program {     delegate void Action();     static void Main(string[] args)     {         List&lt;Action&gt; actions = new List&lt;Action&gt;();          for (int i = 0; i &lt; 10; ++i )             actions.Add(()=&gt;Console.WriteLine(i));          foreach (Action a in actions)             a();     } }   Obviously, the generated class behind the lambda is storing a reference or pointer to the int i variable, and is assigning a new value to the same reference every time the loop iterates.  Is there a way to force the lamda to grab a copy instead, like the C++0x syntax  [&amp;](){ ... } // Capture by reference   vs.  [=](){ ... } // Capture copies
102653
I have below trigger code where I get "List has No Rows for Assignment to SObject"  Apex trigger:  trigger CallVisibility on Compliance_Incident_Transaction_abv__c(before insert, before update) {      // List&lt;Compliance_Incident_Transaction_abv__c&gt; olis = [SELECT Id, Call_Account_abv__c,Call_Load_abv__c, Account_abv__c,Ownerid FROM Compliance_Incident_Transaction_abv__c WHERE Id IN: Trigger.newMap.keySet()];      for (Compliance_Incident_Transaction_abv__c o: Trigger.new) {          //System.debug(o.Order_Phase__r.Order__Item__r.Order_Project__c);         String Terr=[select territoryId from userterritory where userid=:o.Ownerid].territoryid;         String TerrName=[select name from Territory where Id=:Terr].Name;         if(o.Call_Account_abv__c!=null) {             String ATL= [select Territory_vod__c from Account_Territory_Loader_vod__c where Account_vod__c=:o.Call_Account_abv__c limit 1].territory_vod__c; // This line throws error             if(ATL.contains(TerrName))                 {o.Call_Load_abv__c=true;}          }     } }
118273
I'm trying to parse json response.. but keep getting this error      Invalid conversion from runtime type List ANY> to Map String,ANY>   Map&lt;String, Object&gt; MapLv3 = new Map&lt;String, Object&gt;();      Integer x2 = 0; for (Object oh : CallsList){     MapLv3.put(String.valueof(x2), oh);     x2++; } index = x2; System.debug('Map Lv 3 ==&gt;'+MapLv3);  Map&lt;String, Map &lt;String, Object&gt;&gt; Map3 = new Map&lt;String, Map &lt;String, Object&gt;&gt;(); for (Integer a2 = 0; a2 &lt; index; a2++){     Map3.put(String.valueof(a2),(Map&lt;String,Object&gt;) MapLv3.get(String.valueof(a2))); } System.debug('Segment ==&gt;'+Map3.get('0').get('segments'));
10282
I am having an html email template which uses certain merge fields from a custom object. Now I am using following apex code to send certain emails to users.  Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();          mail.setTargetObjectId(t.OwnerId);          mail.setTemplateId(et.Id);         mail.setWhatId(t.Id);          mail.SaveAsActivity = false;         Messaging.sendEmail(new Messaging.singleemailMessage[] {mail});   Code is saved without error but when I run it it says "can't use whatId when sending email to users". Can anyone explain me how to overcome this error? When I use a visualforce template then same code works fine.
31438
Can anyone please help me to understand the below code. I am not able to understand how we are  extracting value from map on visualforce page.  Actually i am trying to get the size of value list which is associated with respective key in map.              &lt;apex:outputPanel &gt;                 &lt;apex:repeat value="{!attributeWrapper.mapAllAttributesLabel}" var="M"&gt;                     &lt;div&gt;                         &lt;div&gt;{!attributeWrapper.mapLabels[M].Name} &lt;/div&gt;                         &lt;div&gt;                             &lt;ul&gt;                                 &lt;apex:repeat value="{!attributeWrapper.mapAllAttributesLabel[M]}" var="attribute"&gt;                                     &lt;li&gt;                                     &lt;p&gt;                                         &lt;apex:outputLink onclick="selectAttribute('{!attribute.attributeLabel.Label__c}','{!attribute.attributeLabel.Attribute__c}');return false;"&gt;                                            &lt;apex:outputLabel value="{!attribute.attributeLabel.Attribute__r.Name}"/&gt;                                         &lt;/apex:outputLink&gt;                                     &lt;/p&gt;                                     &lt;/li&gt;                                 &lt;/apex:repeat&gt;                             &lt;/ul&gt;                         &lt;/div&gt;                     &lt;/div&gt;                 &lt;/apex:repeat&gt;             &lt;/apex:outputPanel&gt;    public with sharing class AttributeWrapper {      public Map&lt;String, List&lt;AttributesLabelWrapper&gt;&gt; mapAllAttributesLabel{       // some code to populate this map     } }   If i do:  {!attributeWrapper.mapAllAttributesLabel[M].size}   I get an error so how do i get the size of value list on VF page?
90357
I am trying to tidy up some really bad legacy code from an old developer and I'm trying to get rid of these nested for loops. The code below shows what I'm currently working with. I've fixed this before with nested SOQL queries but nothing like this. How would this need to look to remove these for loops (except Trigger.New)? Would I use Maps? How would I do that?  map&lt;Id,SObject&gt; mapProperyIdBudDetail = util.GetObjFields(setPropertyId, 'Property'); map&lt;Id,SObject&gt; mapSpaceIdBudDetail = util.GetObjFields( PropertyMap.keyset(), 'Space');  for ( Lease__c l: Trigger.New ) {      if(mapProperyIdBudDetail.get(PropertyMap.get(l.space__c))!=null) {          lProperties = new List&lt;SObject&gt;{mapProperyIdBudDetail.get(PropertyMap.get(l.space__c))};              for ( SObject p: lProperties ) {                  for ( String fm: FieldMap.keyset() ) {                      if ( p.get(FieldMap.get(fm)) != Null) {                         l.put(fm,p.get(FieldMap.get(fm)));                     }                  }             }     } }
9803
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, navigate to the  tag. This question and answer is owned by the community! If you can improve it and make it more useful, you're welcome to edit it. I have a collection of records, like a List&lt;sObject&gt; or the Trigger.new context variable. I need to query other records that are related to these records either directly or indirectly, and I want to use the related data to make further updates. When I write a query in a loop, like for (Account a : Trigger.new) {     Account parent = [SELECT Name FROM Account WHERE Id = :a.ParentId];     // ... }  I keep hitting Salesforce query limits, and I know this is not best practice. What can I do to avoid this problem and bulkify my code?
118936
I am trying to follow the best practice design patterns for triggers but get the error Constructor not defined: [CaseTriggerHandler].(). What am I missing?  Trigger  trigger CaseTrigger on Case (before insert, before update, before delete, after insert, after update, after delete, after undelete) {      CaseTriggerHandler handler = new CaseTriggerHandler();      //Before Insert     if(Trigger.isInsert &amp;&amp; Trigger.isBefore){         handler.OnBeforeInsert(Trigger.new);     }     //After Insert     else if(Trigger.isInsert &amp;&amp; Trigger.isAfter){         handler.OnAfterInsert(Trigger.new);     }     //Before Update     else if(Trigger.isUpdate &amp;&amp; Trigger.isBefore){         handler.OnBeforeUpdate(Trigger.old, Trigger.new, Trigger.newMap);     }     //After Update     else if(Trigger.isUpdate &amp;&amp; Trigger.isAfter){         handler.OnAfterUpdate(Trigger.old, Trigger.new, Trigger.newMap);     }     //Before Delete     else if(Trigger.isDelete &amp;&amp; Trigger.isBefore){         handler.OnBeforeDelete(Trigger.old, Trigger.oldMap);     }     //After Delete     else if(Trigger.isDelete &amp;&amp; Trigger.isAfter){         handler.OnAfterDelete(Trigger.old, Trigger.oldMap);     }     //After Undelete     else if(Trigger.isUnDelete){         handler.OnUndelete(Trigger.new);     } }   Handler      public with sharing class CaseTriggerHandler {      private boolean isExecuting = false;      public CaseTriggerHandler(boolean isExecuting){         this.isExecuting = isExecuting;     }      public void OnBeforeInsert(List&lt;Case&gt; newCases){         //EXECUTE BEFORE INSERT LOGIC     }      public void OnAfterInsert(List&lt;Case&gt; newCases){         //EXECUTE AFTER INSERT LOGIC     }      public void OnBeforeUpdate(List&lt;Case&gt; oldCases, List&lt;Case&gt; updatedCases, Map&lt;Id, Case&gt; CaseMap){         //BEFORE UPDATE LOGIC     }      public void OnAfterUpdate(List&lt;Case&gt; oldCases, List&lt;Case&gt; updatedCases, Map&lt;Id, Case&gt; CaseMap){         //AFTER UPDATE LOGIC     }      public void OnBeforeDelete(List&lt;Case&gt; CasesToDelete, Map&lt;Id, Case&gt; CaseMap){         //BEFORE DELETE LOGIC     }      public void OnAfterDelete(List&lt;Case&gt; deletedCases, Map&lt;Id, Case&gt; CaseMap){         //AFTER DELETE LOGIC     }      public void OnUndelete(List&lt;Case&gt; restoredCases){         //AFTER UNDELETE LOGIC     }      public boolean IsTriggerContext{         get{ return isExecuting;}     } }
90260
We have a workflow that creates tasks and assigns them to a specific user when an opportunity is closed. It's salesforce standard behavior that when the account owner is changed, the open tasks are also reassigned to the new account owner. I'm trying to write a trigger that:   checks if the account owner and/or task owner is changed FROM 00590000000a3xU if yes, reassign the tasks back to 00590000000a3xU only open tasks and tasks where Orb Team Task (checkbox) is true will be reassigned   I was getting all sorts of errors from the old code even after making the changes sfdcfox's pointed out. So I decided to change my approach. Here's the new and working code:  trigger AssignTaskBackToWarehouse on Account (after update){ List&lt;Task&gt;TasksToUpdate = new List&lt;Task&gt;(); Map&lt;Id,Account&gt;amap = new Map&lt;Id,Account&gt;([SELECT Id, OwnerId,(SELECT Id, Status, Warehouse_Task__c     FROM tasks     WHERE Status != 'Completed' AND     Warehouse_Task__c = true)     FROM Account     WHERE Id =: Trigger.newmap.keyset()]); for(Account a : Trigger.new){     for(Task t : amap.get(a.Id).tasks){         t.OwnerId = '00590000000XXXX';         TasksToUpdate.add(t);     }     } if(TasksToUpdate.size() &gt; 0){     update TasksToUpdate; } }
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
81052
// Insert an account  Account a = new Account(Name='Test',                      annualRevenue=100.0);  insert a;  // Create an approval request for the account Approval.ProcessSubmitRequest req1 =        new Approval.ProcessSubmitRequest(); req1.setObjectId(a.id); req1.setNextApproverIds(new Id[] {'***************'}); // Submit the approval request for the account Approval.ProcessResult result =                     Approval.process(req1);   Am trying to execute this code in anonymous block. How ever when tried in trigger i got same error all the time. Hard coded next approvers ID. No luck.  Any suggestions on what am I doing wrong ? Please help!!
85236
Here is my complete code sample   global class b1 implements Database.Batchable&lt;sObject&gt; {   global final string query;  global final string s_object;  global final string field;  global final string field_value;   global b1 (string q, string s, string f, string v){        Query =q;        s_object=s;        field = f;       field_value =v;    }    global Database.QueryLocator start (Database.BatchableContext BC){   return Database.getQueryLocator (query);   }    global void excute(Database.BatchableContext BC, List&lt;sObject&gt; batch) {   for(s_object o= batch){   o.put(field,field_valu);    }   update batch;   }     global void finish(Database.BatchableContext BC){    } }
51297
I moved a method that sets addError() from a trigger into a Helper class. As I started writing test code for it it seems like the addError() is not actually preventing DML operations for the records that get modified in the helper class.  The information from the SF  states: Marks a trigger record with a custom error message and prevents any DML operation from occurring.  Does this mean that addError() will not work outside of a trigger class?  EDIT  Adding some sample code.  public class MyHelperClass() {     public static void someMethod(Opportunity opp) {         opp.My_Field__c.addError('Some error');         insert opp;     } }   And sample test for it without any asserts:  @IsTest private class MyHelperClass_Test() {     @IsTest     static void someTest() {         Opportunity opp = new Opportunity();         opp.Name = 'Some Name';         opp.StageName = 'Prospect';         opp.CloseDate = Date.today().addDays(30);          MyHelperClass.someMethod(opp);     } }   The above inserts the opportunity and does not trigger an exception. Am I doing something wrong?