8

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!

  • Great @eyescream, was driving me nuts, thanks. Post as an answer and I'll accept. – Phil Hawthorn Nov 1 '12 at 11:02
21

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

mike.ProfileId = '00Ee0000000LhpB';

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.