3

I have the following query that is supposed to find all the entered data (Contact List) within the range of 2017 and 2016 ( which for some reason returning 2015 back) and see if the Firstname is empty copy the last name and enter it there. but every time I run this inside the

Developer Console -> Debug -> Open Execute Anonymous Window , it stops and gives me error, and says the required field is missing

"Line: 8, Column: 1 System.DmlException: Update failed. First exception on row 82 with id 0031600002B3oy7AAB; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, First name MUST be entered: []"

for(List<Contact> conList :[SELECT Id,FirstName,LastName,Contact_type__c, Commission_Spiff__c FROM Contact Contact WHERE ( CreatedDate < 2017-03-09T14:19:25.000Z   OR CreatedDate > 2016-12-01T14:19:25.000Z)])
 {
  for(Contact ob: conList)
   {        
   if(ob.FirstName == NULL){
      ob.FirstName = ob.LastName; 

   }             

}
  update conList;
}

Contact Validation Rule

Error Condition Formula ISBLANK(FirstName) Error Message First name MUST be entered

3
  • Could you specify the validation rule which you have on Contact Firstname field ?
    – Lakshman
    Mar 13, 2017 at 19:13
  • @Lakshman hi, yes I just updated the question but basically in contact object I have ISBLANK(FirstName)
    – Metawaa
    Mar 13, 2017 at 19:19
  • 1
    NULL and EmptyString are two different things. I think the solution posted below should help you out.
    – abhi
    Mar 13, 2017 at 19:25

2 Answers 2

1

I think you also need to check the length of FirstName

for(List<Contact> conList :[SELECT Id,FirstName,LastName,Contact_type__c, Commission_Spiff__c 
FROM Contact Contact 
WHERE ( CreatedDate < 2017-03-09T14:19:25.000Z   AND CreatedDate > 2016-12-01T14:19:25.000Z)])
     {
      for(Contact ob: conList)
       {        
       if(ob.FirstName == NULL || ob.FirstName.trim().length()==0){
          ob.FirstName = ob.LastName; 
       } 
    }
      update conList;
    }
0
2

Two issues here:

  1. Your query is returning 2015 results because your WHERE condition is satisfied by any record created before March 9 2017 OR after Dec 1 2016. 2015 is before 2017, so the first condition is met. To fix this, just change OR to AND so it only returns records meeting both criteria.

  2. You are likely running up against the validation rule because the conditional inside your for loop only fixes records where first name is NULL, which is not the same thing as blank. You can use the isBlank String method to check for null and blank at the same time.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.