0

I have a command button inside vf page, which is used to send email to contact. after sending email, I want to display alert message with total no of Contacts.

I'm successfully able to send email but in alert contact list is always zero.

I guess my oncomplete is getting executed as soon as action method is getting called

<apex:commandButton value="Send Email" action="{!sendEmail}"
                         oncomplete="afterSendingEmail()"/>
            
            </div>
     </apex:form>
    
     <script>
    function afterSendingEmail(){
     
        if('{!contactList.size}' == 0){ 
            
            alert('No contact');
        }
        else {
        alert('Email has been sent');  
      } 
    }
  </script> 

controller:

public List<Contact> contactList{ get; set; }
public void sendEmail(){
        
        
         contactList= [Select Id, Email FROM Contact WHERE field__c= :recordID];
         
         List<Messaging.SingleEmailMessage> allmsg = new List<Messaging.SingleEmailMessage>();
         for(Contact con: contactList){
             Messaging.SingleEmailMessage singleEmail = sendEmail(con);
             allmsg.add(singleEmail);
         }
         
         try {
             if(contactList.size()>0){ 
                        Messaging.sendEmail(allmsg,false);
                 
             }
    } 

1 Answer 1

1

{!contactList.size} reflects the initial value of contactList as it is in the constructor (where it doesn't appear to have been initialized) before the sendEmail method is called.

You can solve it by initializing contactList in the constructor. This shouldn't be a problem because the sendEmail method isn't doing anything that will affect the results of the contactList query.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .