+ Start a Discussion
Joe HayesJoe Hayes 

If statement to set variable

I am looking to set a variable depending on the value of a field.

EmailTemplate template = 
    if(a__c == 'a' || a__c == 'b'){
    [SELECT Id, Subject, HtmlValue, Body FROM EmailTemplate WHERE Name = 'ab_Email']}
    else {
    [SELECT Id, Subject, HtmlValue, Body FROM EmailTemplate WHERE Name = 'c_Email']};

Please can someone show me the correct way to do this?

Thank you
Joe
Best Answer chosen by Joe Hayes
alsinan nazimalsinan nazim
Hi Joe,

Are you looking for something like this?
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String devName;
if(field1__c == 'a'){
devName = 'a_Email';
}
else if(field2__c == 'b'){
devName = 'b_Email';
}
if(devName  != null){
EmailTemplate et = [SELECT id FROM EmailTemplate WHERE developerName =: devName];
mail.setSenderDisplayName('Your Name');
mail.setTargetObjectId('Recipient Id');
mail.setTemplateId(et.id);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
}
Add your conditions for selecting the template.
Hope this helps.
 

All Answers

Dmitry OfitserovDmitry Ofitserov
Hi Joe,
One of the ways to do it is :
EmailTemplate template = null;
if(a__c == 'a' || a__c == 'b'){
  tmpList =  [SELECT Id, Subject, HtmlValue, Body FROM EmailTemplate WHERE Name = 'ab_Email' LIMIT 1];
}else{
  tmpList =  [SELECT Id, Subject, HtmlValue, Body FROM EmailTemplate WHERE Name = 'c_Email' LIMIT 1];
}

But you have to be careful here because one of the queries can return "List has no rows to assign..." exception in case there are no records returned by SOQL.
alsinan nazimalsinan nazim
Hi Joe,

Are you looking for something like this?
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String devName;
if(field1__c == 'a'){
devName = 'a_Email';
}
else if(field2__c == 'b'){
devName = 'b_Email';
}
if(devName  != null){
EmailTemplate et = [SELECT id FROM EmailTemplate WHERE developerName =: devName];
mail.setSenderDisplayName('Your Name');
mail.setTargetObjectId('Recipient Id');
mail.setTemplateId(et.id);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
}
Add your conditions for selecting the template.
Hope this helps.
 
This was selected as the best answer