2

Test data creation:

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

Contact con = new Contact(FirstName = 'TestFname1',LastName = 'TestLname1', Email = '[email protected]', 
                              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?

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

1 Answer 1

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 = '[email protected]', 
                              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);
4
  • But, by just calling the User object wont work here? Is this the only(query back) way again? Commented Sep 19, 2017 at 19:47
  • 2
    you could not retrieve reference field values until you execute a separate query Commented Sep 19, 2017 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() Commented Sep 20, 2017 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. Commented Sep 20, 2017 at 19:45

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .