0

I have the next code on my test Class:

parentAcc.ExternalId = '001';

insert parentAcc;

System.debug('parentAcc ExternalId' + parentAcc.ExternalId);

childAccount.ParentId = parentAcc.id;

insert childAccount;

System.debug('childAccount Parent ExternalId' + childAccount.Parent.ExternalId);

//DEBUGS
// parentAcc ExternalId 001
// childAccount Parent ExternalId null

If I search for childAccount.ParentId, it shows correctly the Id of the inserted parentAcc. If I search this information in accounts that I already have on my org, and their shows correctly the field Parent.ExternalId of their respective parent accounts.

So, I don't understand what is happening.

2

If you're trying to access data on a related record (parent, grandparent, etc...), then you need to query for it.

So if you'd do childAccount = [SELECT Id, Parent.ExternalId FROM Account WHERE Id = :childAccount.Id]; (after inserting the child record, obviously), your debug would print the value.

The exception to that is if you set the parent "name pointing reference" yourself.

Account child = new Account(
    Name = 'A Child', 
    // Note that we're setting the 'Parent' 'field', not ParentId
    // If this were a custom relationship field, you'd use Parent__r instead of
    //   Parent__c
    Parent = new Account(External_Id_Field__c = 'value')
);

system.debug(child.Parent.External_Id_Field__c); // would print 'value'

insert child;

system.debug(child.Parent.External_Id_Field__c); // would still print 'value'

Note that we're not allowed to set both the relationship field (ParentId) as well as the name pointing reference (Parent) if you want to perform dml on the record. This approach can be used to relate a record to a parent without knowing the parent's Salesforce-generated Id, but be aware that doing so requires that the external Id be unique on the target object, and that the external Id is the only thing you can set in the object instance used for the name pointing reference.

2
  • That's a useful information , thanks, but then I have another doubt: What happen if I want to access Parent.ExternalId without having to insert the child object firstly? I need this data but in a before insert context.
    – CPS
    Jun 17 at 12:54
  • @CPS I'm not quite sure what you're asking here, and this is beginning to sound like an X-Y problem. This is starting to sound like you should make another question (and focus on the overall goal you're trying to achieve). My example code shows that you can access Parent.ExternalId prior to inserting the child account (though I'm not sure what good that information could do prior to the record being inserted).
    – Derek F
    Jun 17 at 13:26

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.