You can populate lookup fields using an object with an external id field populated like so:

Custom_Object__c o = new Custom_Object__c(Account__r=new Account(External_ID__c='123'));
insert o; 

However, when I want to dynamically assign values using the .put method instead of the property, I receive an error:

Custom_Object__c co = new Custom_Object__c();
SObject new_obj = co.newSObject();
new_obj.put('Account__r', new Account(External_ID__c='123'));

From the above code I receive Invalid field Account__r for Custom_Object__c

1 Answer 1


You are so close, this is not because you are using an External Id, it is because you are not using the right SObject method.

I have been caught out by this many times as well.

The correct syntax is:

new_obj.putSObject('Account__r', new Account(External_ID__c='123'));
  • I've used this method before; I don't know why I didn't check the method signatures on the sobject when I was looking through the documentation last night. Thanks! Jul 3, 2013 at 12:43
  • Can we use the same concept with Owner if I have a external Id on the user?
    – brovasi
    Sep 15, 2014 at 12:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.