I have tried adding {!EmailMessage.Subject} in the subject line of the reply template which I am specifically using to reply to the existing emails from Salesforce. This helps me to retain the subject without it being overwritten by the template selection. The only drawback here is that it would retain the original subject line and not the lates subject line, but I can live with it as of now. SOMETHING IS BETTER THAN NOTHING I guess...
You'll probably want to use Messaging.renderStoredEmailTemplate instead:
Messaging.SingleEmailMessage m =
Messaging.renderStoredEmailTemplate(template.Id, record.ContactId, record.Id);
Note that because the ID won't be available before insert, you won't be able to get a thread ID before insert, either; you'll need to use the after-insert, before-update trick, instead:
trigger SetCaseSubject on Case (after insert, before update) {
if(Trigger.isAfter) {
update Trigger.new.deepClone(true, false, false);
} else {
EmailTemplate template = [SELECT Id FROM EmailTemplate WHERE ...].Id;
for(Case record: Trigger.new) {
record.Subject = Messaging.renderStoredEmailTemplate(template.Id, record.ContactId, record.Id).getSubject();
}
}
}
Note: If you want the subject updated only the first time, you can use the after-insert trigger to update the records. You are allowed a single recursive update after insert to perform an update, but you cannot perform an update on a record in after-update.
N.B. You will want to limit yourself from doing mass inserts if you do this; each Messaging.renderStoredEmailTemplate will use at least one query, so this falls under the "query in a loop" anti-pattern.
Best Answer
The VF Email Template that you have designed,you can add
<messaging:emailTemplate>
tag in it at top.It will help you to add subject name dynamically if you are want to add field value in your subject line. Below is the example that explains how you can use above tag.recipientType & relatedToType are optional.