2

Test data creation:

Account acct = new Account(Name='TestAccount', Field__c='TestInfo');
    insert acct;

Contact con = new Contact(FirstName = 'TestFname1',LastName = 'TestLname1', Email = 'test@gmail.com', 
                              AccountId = acct.Id);
    insert con; 
Profile p = [SELECT Id FROM Profile WHERE Name = 'Custom Profile'];
User u = new User(/* Standard and Custom fields*/, ContactId = con.Id);

System.debug('user.contactId: ' +u.ContactId);
System.debug('user.con.FirstName: ' +u.Contact.FirstName);

I can able to get the ContactId, but not the FirstName. How to get the Firstname and other fields(User.Contact.Account.Name)?

I tried to query: Select Contact.FirstName from User which is working as expected, but why I cannot get this in my test data?

  • It is the Salesforce out-of-box User object's lookup field to the Contact object. – Austin Evans Sep 19 '17 at 19:43
  • 2
    Unless you queried for the data back, you won't have access to the value. – sfdcfox Sep 19 '17 at 19:45
4

You have created an instance of the user. Insert user record and separately perform SOQL query to retrieve Contact.FirstName

Account acct = new Account(Name='TestAccount', Field__c='TestInfo');
    insert acct;

Contact con = new Contact(FirstName = 'TestFname1',LastName = 'TestLname1', Email = 'test@gmail.com', 
                              AccountId = acct.Id);
    insert con; 
Profile p = [SELECT Id FROM Profile WHERE Name = 'Custom Profile'];
User u = new User(/* Standard and Custom fields*/, ContactId = con.Id);
insert u;    

System.debug('user.contactId: ' +u.ContactId);

//retrieve user record by SOQL
User userObj = [SELECT Contact.FirstName FROM User WHERE Id =:u.Id];

System.debug('user.con.FirstName: ' +userObj.Contact.FirstName);
| improve this answer | |
  • But, by just calling the User object wont work here? Is this the only(query back) way again? – Austin Evans Sep 19 '17 at 19:47
  • 2
    you could not retrieve reference field values until you execute a separate query – Santanu Boral Sep 19 '17 at 19:49
  • I thing you will get Mixed DML Exception because you are inserting setup and non setup object same time. use System.RunAs() – cloudZigZag Sep 20 '17 at 8:54
  • Well, I am actually trying to see/check the value that returns. Anyways I am using asserts statements to compare the values under System.runAs( ). Thanks for the heads-up. – Austin Evans Sep 20 '17 at 19:45

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.