Print this page

UserType captured as NULL in before insert trigger

Knowledge Article Number 000233437
Description As per the Developer Guide for User Object, each UserType is associated with one or more UserLicense records. Each UserLicense is associated with one or more profiles.But when trying to insert a user using UserType, it results as NULL. 
 
Resolution This is working as designed. When inserting users via apex, since the license type is not specified directly (and is specified indirectly through the profileId), the license has not been allocated/assigned to the user yet in before insert trigger. On the contrary, while creating users via UI, the license type is selected as part of the UI before a profileId can be selected. 

You can get the userType via following query in before insert trigger: 
[select id, name, usertype from profile where id=:u.profileId limit 1].UserType

We have some workarounds for this: 
  1. Use ProfileId instead of Usertype as the profile determines the UserType (since it's the UserLicense.Name in the Profile that's really being read), and the profileId is specified in the Apex code that creates the User. This is highly recommended. 
  2. Use the query to get the UserType via following query in before insert trigger: [select id, name, usertype from profile where id=:u.profileId limit 1].UserType 
  3. Keep the same code but use in after Insert trigger after testing all your logic can be used in after insert trigger 

 




promote demote