+ Start a Discussion
SFDC HedgehogSFDC Hedgehog 

INVALID_CROSS_REFERENCE_KEY on email in Custom Button javascript

Hi all,

I've scoured the net but nothing seems to work....
I have a custom object (Account_Request__c).
I have a Detail page Button.

This is the source to the button;
 
{!REQUIRESCRIPT("/soap/ajax/30.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/29.0/apex.js")}

var message = new sforce.SingleEmailMessage();
var xKey = "{!Account_Request__c.Id}";
message.replyTo = "sfdchedgehog@gmail.com";
message.toAddresses = ["toaddress@gmail.com"];
message.targetObjectId = xKey;
message.templateId = "00Xe0000000M2FH";  // valid template ID - I checked
message.saveAsActivity = false;    // eventually I want to set to "true"
var result = sforce.connection.sendEmail([message]);
if(result[0].success != 'true') {
alert(result[0].errors);
}

And I always get an error back that says
{message:'invalid cross reference id', statusCode:'INVALID_CROSS_REFERENCE_KEY', targetObjectId:null, }
I made sure the Account_Request__c object has activities enabled.  My org does NOT have cross-scripting enabled  (I'm wondering if that has something to do with this.)-  And I made sure the Account_Request__c ID is not null. 

Any ideas about what I'm doing wrong?

I can auto-populate a template with all the Account_Request__c info from the "Send an Email" button on the activities related list, but I keep getting an error on autosave, so I'm trying to find a way around that.   Any ideas are welcome.

Thanks!
 
James LoghryJames Loghry
The targetObjectId has been around for quite some time and is a rather misleading name as far as variables go, along with its related exceptions, in my opinion.  However, targetObjectId needs to be either a User, Lead, or Contact record, and if specified, it represents who the email will be sent to.  This gives email templates the ability to pull in stuff like Dear {!FirstName} where FirstName is the targetObject's field.

I believe what you want instead of (or in addition to) is the WhatId for the Account_Request__c.Id field. 

More info on the targetObjectId and WhatId fields can be found here: https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_sendemail.htm
SFDC HedgehogSFDC Hedgehog
Thanks for the reply James.
It looks like I might have to come up with a VF page, or do something exotic like set a checkbox and have a workflow take care of the email.
What's sinking me now is from this page;  https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_sendemail.htm

User-added image

....Apparently custom objects are not coming to the party.