Find your content:

Search form

You are here

Creating a user with DML

 
Share

I have the following Apex code:

User mike = new User();
mike.Username= 'mike.white@company.com';
mike.Email = 'mike.white@company.com';
mike.Lastname = 'mike';
mike.Firstname = 'white';
mike.Alias = 'mwhite';
mike.CommunityNickname = 'mwhite01';
mike.UserRole = [ select id from userrole where id ='00Ee0000000LhpB' ];
mike.Profile = [ select id from profile where id = '00ee0000000Hfng' ];

mike.CurrencyIsoCode = 'USD';
mike.TimeZoneSidKey = 'GMT';
mike.LocaleSidKey = 'en_US';
mike.EmailEncodingKey = 'ISO-8859-1';
mike.LanguageLocaleKey = 'en_US';
mike.UserPermissionsMobileUser = false;

System.debug ( JSON.serializePretty( mike ) );

insert mike;

Which throws the following error:

System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Profile]: [Profile]

Which is confusing, because I echo 'mike' before I try the insert which clearly shows the Profile present:

{
  "attributes" : {
    "type" : "User"
  },
  "CurrencyIsoCode" : "USD",
  "TimeZoneSidKey" : "GMT",
  "LanguageLocaleKey" : "en_US",
  "Profile" : {
    "attributes" : {
      "type" : "Profile",
      "url" : "/services/data/v26.0/sobjects/Profile/00ee0000000HfngAAC"
    },
    "Id" : "00ee0000000HfngAAC",
    "Name" : "inTime T&E"
  },
  "LocaleSidKey" : "en_US",
  "LastName" : "mike",
  "UserRole" : {
    "attributes" : {
      "type" : "UserRole",
      "url" : "/services/data/v26.0/sobjects/UserRole/00Ee0000000LhpBEAS"
    },
    "Id" : "00Ee0000000LhpBEAS",
    "Name" : "inTime Resource"
  },
  "EmailEncodingKey" : "ISO-8859-1",
  "Email" : "mike.white@company.com",
  "Alias" : "mwhite",
  "Username" : "mike.white@company.com",
  "FirstName" : "white",
  "CommunityNickname" : "mwhite01",
  "UserPermissionsMobileUser" : false
}

I guess I'm missing something basic, but can't figure out what. Thanks!


Attribution to: Phil Hawthorn

Possible Suggestion/Solution #1

Actual field names are User.ProfileId and UserRoleId. Assign the strings directly:

mike.ProfileId = '00Ee0000000LhpB';

Attribution to: eyescream
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/3967

My Block Status

My Block Content