I have overridden the standard view of Account object with a visualforce page,& using a custom button that is used to send email to Account,using a custom field,Email__c.The error appears if we've not filled the Email__c field & try to send email.On reload of page showing the error,I want the message to be removed.But the page appears again with the error message.What can I do?
My code is as follows:
public with sharing class sendEmailToAccount {
ApexPages.StandardController controller;
public sendEmailToAccount(ApexPages.StandardController controller) {
this.controller = controller;
}
public PageReference sendEmailToAccount() {
Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
List<Account> lstaccount = [select id,Test_Email_Field__c,Name,AccountNumber from Account where id = :ApexPages.currentPage().getParameters().get('id')];
if(lstaccount[0].Test_Email_Field__c==null)
{
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Cannot Send email when Email field is empty.'));
return null;
}
if(lstaccount[0].Test_Email_Field__c!=null)
{
String accName=String.valueOf(lstaccount[0].Name);
String accNumber=String.valueOf(lstaccount[0].AccountNumber);
String accOwner=String.valueOf(lstaccount[0].Name);
String toAddress=String.valueOf(lstaccount[0].Test_Email_Field__c);
EmailTemplate et=[select Id, subject,body,HtmlValue from EmailTemplate where id='00X28000000R3VZ'];
String subjectTemplate= et.subject;
String contentTemplate=et.body;
String htmlcontent=et.HtmlValue;
String filteredcontent=contentTemplate.replace('{!Account.Name}',accName);
String filteredcontent1=filteredcontent.replace('{!Account.Id}',accOwner);
String filteredcontent2=filteredcontent1.replace('{!Account.AccountNumber}',accNumber);
message.ToAddresses=new String[]{toAddress};
message.subject=subjectTemplate;
message.PlainTextBody=filteredcontent2;
message.HtmlBody=htmlcontent;
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.Confirm,'Email sent successfully !'));
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { message });
return null;
}
return controller.view();
}
}
VF Page
<apex:page standardController="Account" extensions="sendEmailToAccount" action="{!sendEmailToAccount}">
<apex:pageMessages id="messages" />
<apex:detail relatedList="true"/>
</apex:page>
JavaScript Code:
if(confirm("Are you sure You want to send Email?"))
{
window.open('/apex/SendEmailToAccount?id={!Account.Id}','_self');
}
sendEmailToAccount
method getting invoked?sendEmailToAccount
method from apex:page action attribute. On page load it will always check for the Account email address and if address is not present then it will give error.. I think you can just use that javascript button and show alert message if email is null and you could use webservice for sending emails