function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
banders5144banders5144 

resolve foreign keys by external ID or idLookup FIeld

I am quoting apex documentation:

 

Example 1

 

In addition, the sObject field key can be used with insertupdate, or upsert to resolve foreign keys by external ID. For example:

  Account refAcct = new Account(externalId__c = '12345');

  Contact c = new Contact(account = refAcct, lastName = 'Kay');

 

Example 2

 

 

For example, suppose that custom object C1 has a foreign key c2__c that links to a child custom object C2. You want to create a C1 object and have it associated with a C2 record named 'xxx' (assigned to the value c2__r). You do not need the ID of the 'xxx' record, as it is populated through the relationship of parent to child. For example:

 

insert new C1__c(name = 'x', c2__r = new C2__c(name = 'xxx')); 

 

Now i have used this method a couple of times for different object relationship but the only one that i have not gotten to work is with Who or What relationships. Example:

insert new Task(name = 'test', subject = 'test', What = new Account(extid__c = 'test'));

 

Has anyone ever gotten this to work?

 

banders5144banders5144

Anyone?

SuperfellSuperfell

It should work, how does it fail ?

banders5144banders5144

running this line of code;

 

insert new Task(name = 'test', subject = 'test', What = new Account(ext_id__c = 'test'));

 

gives me this error:

 

Compile Error: line 1, column 24: Invalid field name for SObject Task

banders5144banders5144

Anyone?

SuperfellSuperfell

There's no field called name on Task, but when you fix that you'll get another error saying that What isn't writable, not sure why there's that restriction in apex.