Create a Salesforce User in Apex with all Required Fields Populated



Create a Salesforce User with Code in Apex with all of the Required Fields Populated for a Test Class



When attempting to create a user with code in Apex you will encounter an error if you do not populate every single required field. You may be attempting to do this for a Test class or for any number of reasons. The error you encounter may look similar to the following:

Missing fields Exception

System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [LastName, Email, Alias, TimeZoneSidKey, LocaleSidKey, EmailEncodingKey, ProfileId, LanguageLocaleKey]: [LastName, Email, Alias, TimeZoneSidKey, LocaleSidKey, EmailEncodingKey, ProfileId, LanguageLocaleKey]


Create a User




Many of those fields require specific values populated from a picklist. Below is some boilerplate code you can use to create a use programmatically with all of those fields populated correctly. You can use your own values for timezonesidkey and locale if desired. They are listed below.

List of TimeZoneSidKey values you can use

Pacific/Kiritimati
Pacific/Chatham
Pacific/Auckland
Pacific/Enderbury
Pacific/Fiji
Pacific/Tongatapu
Asia/Kamchatka
Pacific/Norfolk
Australia/Lord_Howe
Australia/Sydney
Pacific/Guadalcanal
Australia/Adelaide
Australia/Darwin
Asia/Seoul
Asia/Tokyo
Asia/Hong_Kong
Asia/Kuala_Lumpur
Asia/Manila
Asia/Shanghai
Asia/Singapore
Asia/Taipei
Australia/Perth
Asia/Bangkok
Asia/Ho_Chi_Minh
Asia/Jakarta
Asia/Rangoon
Asia/Dhaka
Asia/Yekaterinburg
Asia/Kathmandu
Asia/Colombo
Asia/Kolkata
Asia/Karachi
Asia/Tashkent
Asia/Kabul
Asia/Dubai
Asia/Tbilisi
Europe/Moscow
Asia/Tehran
Africa/Nairobi
Asia/Baghdad
Asia/Kuwait
Asia/Riyadh
Europe/Minsk
Africa/Cairo
Africa/Johannesburg
Asia/Jerusalem
Europe/Athens
Europe/Bucharest
Europe/Helsinki
Europe/Istanbul
Africa/Algiers
Europe/Amsterdam
Europe/Berlin
Europe/Brussels
Europe/Paris
Europe/Prague
Europe/Rome
Europe/Dublin
Europe/Lisbon
Europe/London
GMT
Atlantic/Cape_Verde
America/Sao_Paulo
Atlantic/South_Georgia
America/Argentina/Buenos_Aires
America/Santiago
America/St_Johns
America/Halifax
America/Puerto_Rico
Atlantic/Bermuda
America/Caracas
America/Bogota
America/Indiana/Indianapolis
America/Lima
America/New_York
America/Panama
America/Chicago
America/El_Salvador
America/Mexico_City
America/Denver ****America/Denver
America/Phoenix
America/Los_Angeles
America/Tijuana
America/Anchorage
Pacific/Honolulu
Pacific/Niue
Pacific/Pago_Pago


List of LocaleSidKey values you can use

sq
sq_AL
ar
ar_BH
ar_EG
ar_JO
ar_KW
ar_LB
ar_QA
ar_SA
ar_AE
hy
hy_AM
az_AZ
eu
eu_ES
be_BY
bn_BD
bs
bs_BA
bg
bg_BG
ca
ca_ES_EURO
ca_ES
zh
zh_CN_PINYIN
zh_CN_STROKE
zh_CN
zh_HK_STROKE
zh_HK
zh_MO
zh_SG
zh_TW_STROKE
zh_TW
hr
hr_HR
cs
cs_CZ
da
da_DK
nl
nl_BE
nl_NL
nl_SR
en_AU
en_BB
en_BM
en_CA
en_GH
en_IN
en_ID
en_IE_EURO
en_IE
en_MY
en_NZ
en_NG
en_PK
en_PH
en_SG
en_ZA
en_GB
en_US
et
et_EE
fi
fi_FI_EURO
fi_FI
fr
fr_BE
fr_CA
fr_FR_EURO
fr_FR
fr_LU
fr_MC
fr_CH
ka
ka_GE
de
de_AT_EURO
de_AT
de_DE_EURO
de_DE
de_LU_EURO
de_LU
de_CH
el
el_GR
iw
iw_IL
hi
hi_IN
hu
hu_HU
is
is_IS
in
in_ID
ga
ga_IE
it
it_IT
it_CH
ja
ja_JP
kk_KZ
km_KH
ky_KG
ko
ko_KR
lv
lv_LV
lt
lt_LT
lb
lb_LU
mk
mk_MK
ms
ms_BN
ms_MY
mt
mt_MT
sh_ME
no
no_NO
pl
pl_PL
pt
pt_AO
pt_BR
pt_PT
ro
ro_MD
ro_RO
rm
rm_CH
ru
ru_RU
sr
sr_BA
sh
sh_BA
sh_CS
sr_CS
sk
sk_SK
sl
sl_SI
es
es_AR
es_BO
es_CL
es_CO
es_CR
es_DO
es_EC
es_SV
es_GT
es_HN
es_MX
es_PA
es_PY
es_PE
es_PR
es_ES_EURO
es_ES
es_UY
es_VE
sv
sv_SE
tl
tl_PH
tg_TJ
th
th_TH
tr
tr_TR
uk
uk_UA
ur
ur_PK
vi
vi_VN
cy
cy_GB


List of EmailEncodingKey values you can use

UTF-8
ISO-8859-1
Shift_JIS
ISO-2022-JP
EUC-JP
ks_c_5601-1987
Big5
GB2312


List of LanguageLocaleKey values you can Use

Chinese (Simplified): zh_CN
Chinese (Traditional): zh_TW
Danish: da
Dutch: nl_NL
English: en_US
Finnish: fi
French: fr
German: de
Italian: it
Japanese: ja
Korean: ko
Portuguese (Brazil): pt_BR
Russian: ru
Spanish: es
Swedish: sv
Thai: th
Arabic: ar
Bulgarian: bg
Czech: cs
English (UK): en_GB
Greek: el
Spanish (Mexico): es_MX
Hebrew: iw
Hungarian: hu
Indonesian: in
Norwegian: no
Polish: pl
Romanian: ro
Turkish: tr
Ukrainian: uk
Vietnamese: vi
Albanian: sq
Armenian: hy
Basque: eu
Bosnian: bs
Croatian: hr
English (Australia): en_AU
English (Canada): en_CA
English (India): en_IN
English (Malaysia): en_MY
English (Philippines): en_PH
Estonian: et
French (Canada): fr_CA
Georgian: ka
Hindi: hi
Icelandic: is
Irish: ga
Latvian: lv
Lithuanian: lt
Luxembourgish: lb
Macedonian: mk
Malay: ms
Maltese: mt
Moldovan: ro_MD
Montenegrin: sh_ME
Portuguese (European): pt_PT
Romansh: rm
Serbian (Cyrillic): sr
Serbian (Latin): sh
Slovak: sk
Slovenian: sl
Tagalog: tl
Urdu: ur
Welsh: cy


Code to create a user in Apex

        User user = new User();
        
        user.FirstName = 'Test';
        user.LastName = 'Name';
        user.CompanyName = 'IT Test Company';
        user.MobilePhone = '123-456-7890';
        
        user.Username = 'testUser-' + generateRandomString() + '@test.com';
        user.Email = 'testUser-' + generateRandomString() + '@test.com';
  user.Alias = 'test';
        user.CommunityNickname = 'test1';
        user.TimeZoneSidKey = 'America/New_York';
        user.LocaleSidKey = 'en_US';
        user.EmailEncodingKey = 'UTF-8';
        user.ProfileId = prof.Id;
        user.LanguageLocaleKey = 'en_US';
        
        user.Street = '123 Test St';
        user.City = 'Testcity';
        user.State = 'va';
        user.PostalCode = '23223';
        user.Country = 'USA';
        
        insert user;


Generate a Random Numeric String

    private static String generateRandomString() {
        return '' + math.rint( math.random() * 100000 );
    }


Here is a link to a user having a similar problem on the Salesforce forums: Creating a user in Apex

Using System.runAs() to Run Code as the User you just Created




After creating that user, you may want to explicitly run code as this user. You may want to check permissions or sharing rules are applying correctly to that user's profile for instance. You can accomplish this using a runAs block and passing in the user you just created.

IsTest Annotation to use Existing Data in Test Class

          System.runAs(user) {
             // The following code runs as user 'u' 
             System.debug('Current User: ' + UserInfo.getUserName());
      // Perform user specific operations here            
          }



More info on the runAs command here: Salesforce runAs Documentation

It is also documented in this Salesforce article: Salesforce Intro to Testing

Avoid Staging User Data by Using Existing Data




Alternatively, you may be able to avoid having to stage user data entirely by using existing data in the database. If you want your Test Class to use existing data in your environment, whether its Sandbox or Test or Prod, you can use the following modification to the isTest annotation:

IsTest Annotation to use Existing Data in Test Class

@IsTest(SeeAllData=true)


Place the annotation above the class declaration for your test class. Then your test class should have access to all of your organization's data in your Salesforce instance. Be sure to consider your use cases when deciding to use existing data or staging new data.

Additional info on the @IsTest annotation: IsTest Annotation

Popular posts from this blog

How to set up a SQL Server 2008 Local Database

Use Chrome for Development and Allow Cross-domain Javascript and AJAX

Spring Boot Internationalization with Default Locale for Message Strings