2

I am referring to this link for relating parent data with external id. Link: Click here

Sample code which I am trying:

ysr_NS_test__Object_Child__c childObjectReference = new ysr_NS_test__Object_Child__c(Name='apex_child1');


ysr_NS_test__Object_Parent__c parentObjectForReference = 
    new ysr_NS_test__Object_Parent__c(ysr_NS_test__Parent_External_Id__c = '1');


childObjectReference.ysr_NS_test__Object_Parent__c = parentObjectForReference.Id;

try{
//insert childObjectReference;
    Database.SaveResult result = Database.insert(childObjectReference);

}
catch(Exception e){
    System.debug('Exception -' + e);
}
  • ysr_NS_test is the namespace.
  • ysr_NS_test__Object_Child__c is the child object which has parent object lookup.
  • ysr_NS_test__Object_Parent__c is the parent object which has external id.

I am expecting parent with external id 1 should bind to child object which is getting created(without querying the parent object).

Update:

Error I am getting:

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

0
2

Constructing a parent record with its External Id field set doesn't magically tell you in memory what the Salesforce Id value is.

You need to set the relationship using the name pointing field:

childObjectReference.ysr_NS_test__Object_Parent__r = new ysr_NS_test__Object_Parent__c(ysr_NS_test__Parent_External_Id__c = '1');

A bit easier to read with renamed objects for clarity:

childRecord.Parent__r = new Parent__c(External__c = '1');
0

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.