Search code examples
salesforceapex-code

setWhatId in salesforce using email template


i have to send an email to a user in salesforce using email template.this template contain merge field type of custom object.

 Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setTargetObjectId(user.get(0).id);


mail.setTargetObjectId(user.get(0).Id)
mail.setTemplateId(specifier.get(0).Template_id__c);
mail.saveAsActivity = false;
mail.setWhatId(custom_object.Id);

i read in documentation If you specify a contact for the targetObjectId field, you can specify a whatId as well. This helps to further ensure that merge fields in the template contain the correct data. The value must be one of the following types: Account Asset Campaign Case Contract Opportunity Order Product Solution Custom

but if we are sending email to a user not to contact then how to assign a custom object for merge field type in custom objects as in the above code


Solution

  • Not sure this is possible to do, but it depends on the relationship between your custom object and your users that will be receiving the merged emails. Do you have a 1-to-1 relationship between User and CustomObject? If so, perhaps adding a reference to the single custom object instance that each user object references and then adding custom formula fields on your user object with CustomObject__r.CustomField__c would do the trick.

    In a custom formula field on your User object:

    TEXT(CustomObject__r.CustomField__c)
    

    Then your template could be changed into a User template and the merge fields would be the formula fields that actually pointed to your custom object instance. But if you have some other relationship like 1-to-many or many-to-many between User and CustomObject__c, I think you're out of luck.