When running the code below anonymously I get a (paraphrased) error:
"Field Custom_Field__c does not exist"
Code:
Id bankId = 'a1e630000000oOG';
Id contactId = '00363000009GnPE';
//verify field exists
Submission__c sub = [SELECT Id, Bank__c FROM Submission__c WHERE Id=:bankId];
//verify record exists and bank field is populated
System.assert(String.valueOf(sub.Bank__c).length()>0);
//verify record exists
System.assert([Select id from contact WHERE id=:contactId].size()==1);
String unrendered = 'Dear {!Bank__c},\n Hope you\'re doing well!';
List<Messaging.RenderEmailTemplateBodyResult> renderResults = Messaging.renderEmailTemplate(contactId, bankId, new List<String>{unrendered});
System.debug(renderResults);
I've made sure the whatId record exists, the field being merged is populated, and the whoId record exists (as can be seen from the assert statements).
But I get an error:
getFieldName=Bank__c;
getMessage=Field Bank__c does not exist. Check spelling.;
getOffset=7;
getStatusCode=EMAIL_TEMPLATE_MERGEFIELD_ERROR;
Here's the full user debug:
13:32:16:146 USER_DEBUG [17]|DEBUG|(Messaging.RenderEmailTemplateBodyResult[getErrors=(Messaging.RenderEmailTemplateError[getFieldName=Bank__c;getMessage=Field Bank__c does not exist. Check spelling.;getOffset=7;getStatusCode=EMAIL_TEMPLATE_MERGEFIELD_ERROR;]);getMergedBody=null;getSuccess=false;])
As seen in the debug log the attribute getMergedBody
is null. I'm trying to merge text on the fly so users can send emails with their choice of fields to merge. Why am I getting this error? What does it actually mean since the field does indeed exist?
Thank you!
Edit:
The field is accessible to the running user as checked on the FLS level.
Edit 2:
This question has already been answered. To reproduce the issue in any org use this code:
Opportunity opp = [SELECT Id, StageName FROM Opportunity LIMIT 1];
Contact con = [Select id from contact LIMIT 1];
Id oppId = opp.Id;
Id contactId = con.Id;
//verify record exists and bank field is populated
System.assert(String.valueOf(opp.StageName).length()>0);
//as per the answer, {!StageName} needs to be changed to {!Opportunity.StageName}
String unrendered = 'Dear {!StageName},\n Hope you\'re doing well!';
List<Messaging.RenderEmailTemplateBodyResult> renderResults = Messaging.renderEmailTemplate(contactId, oppId, new List<String>{unrendered});
System.debug(renderResults);