0

I would like to check at least one user is selected(checkbox checked) when clicking on Send Email button. How to have a conditional logic in the Command button?

       <apex:pageBlockTable value="{!contacts}" var="c" id="table">
            <apex:column >
                <apex:inputCheckbox value="{!c.selected}" id="checked"/>
            </apex:column>
            <apex:column value="{!c.con.Name}" />
            <apex:column value="{!c.con.Email}" />
            <apex:column value="{!c.con.Phone}" />
        </apex:pageBlockTable>
        <apex:pageBlockSection >
            <apex:commandButton value="Send Email" action="{!sendEmail}" onclick="if(!confirm('Do you want to send the email?')){return false;}" onComplete="window.top.location.reload()"/>
        </apex:pageBlockSection>

Solution trying: Sending email to the select contact records. The above pageBlockTable will display all the contact records with provided SOQL query. Implemented using Wrapper class to display contact records with checkboxes.

Now I am trying to validate whether the end user selected(checkboxes) at least one of the listed contacts before executing the sendEmail action. How can I approach that?

2
  • can you update your question trying your conditional logic? – Santanu Boral Aug 25 '17 at 19:34
  • Provided some explanation to the solution I am trying. – Arnold Jr. Aug 25 '17 at 19:41
2

It is pretty conventional to do this validation at the server-side. In your controller:

public PageReference sendEmail() {
    Boolean atLeastOneSelected = false;
    for (WrapperClassName c : contacts) {
        if (c.selected) {
            atLeastOneSelected = true;
            break;
        }
    }
    if (atLeastOneSelected) {
        ... do send ...
    } else {
        // You need an apex:pageMessages in the Visualforce to see this
        ApexPages.addMessage(new ApexPages.Message(
                ApexPages.Severity.ERROR,
                'Select at least one Contact'
                ));
        return null;
    }
}

Best not to interfere by defining your own onComplete; the return value of the controller method will drive what the next page is with null meaning redisplay the current page.

You could do the check at the client-side in JavaScript, but then Visualforce gives you very little help and you have to be pretty good at JavaScript/DOM to do a good job.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.