0

I am new to Salesforce Programming. I was checking ways to update the username field of User record to always match with the Email field.

Can we write a batch class in achieving this? Thoughts

global class BatchUpdateAccount implements Database.Batchable<sObject>{ 

global string query; 
global database.querylocator start(Database.BatchableContext BC){ 
   query = 'select Id,name,username,email from User 
             where Username<>email'; 
   return Database.getQueryLocator(query); 
} 
global void execute(Database.BatchableContext BC, List<User> scope){
 List<User> cons = new List<User>(); 
 for (User s : scope){ 
   s.Username= s.Email; 
   cons.add(s); 
 } 
 update cons; 
} 
global void finish(Database.BatchableContext BC){ } }
  • 1
    Should be possible with batch class. Its like updating any other record. Note: Username is unique field across all salesforce orgs. How would you handle that? Usually people append a prefix at the end of email in username – Raul Mar 21 '17 at 15:21
  • I would like to do it in Prod environment. So that would not require any prefix correct? – user43146 Mar 21 '17 at 15:31
  • In that case it's possible and should be fairly easy. Let us know if you run into any specific issue. – Raul Mar 21 '17 at 15:35
  • You must use try-catch to handle any exception occur. – Ashwani Mar 21 '17 at 15:51
  • The error which I see in the job is First error: expecting a colon, found 'email' – user43146 Mar 21 '17 at 15:55
2

You can't write a SOQL filter to look for User.Usernames that don't agree with User.Email

Instead, if you want to do this in one SOQL, you'll need to create a Checkbox formula field on User that is

Is_UserName_Same_As_UserEmail__c

defined as UserName = Email

and query on that field as in ... where Is_UserName_Same_As_UserEmail__c = true

| improve this answer | |
  • I did try that as well. But it did not work – user43146 Mar 29 '17 at 17:41
  • global class BatchUpdateAccount implements Database.Batchable<sObject>{ global string query; global database.querylocator start(Database.BatchableContext BC){ query = 'select Id,name,username,email from User where Username__c= true'; return Database.getQueryLocator(query); } global void execute(Database.BatchableContext BC, List<User> scope){ List<User> cons = new List<User>(); for (User s : scope){ s.Username= s.Email; cons.add(s); } update cons; } global void finish(Database.BatchableContext BC){ } } – user43146 Mar 29 '17 at 17:51
  • @user43146 - you need to show your formula field for Username__c (BTW, boolean formula fields should usually be of the form IsXXX or HasYYY to indicate through reading into one's mind a true/false statement – cropredy Mar 29 '17 at 21:16
  • The formula field Username__c is Email<>Username – user43146 Apr 6 '17 at 16:21

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.