Getting checked checkboxes values using Salesforce Apex

Getting checked checkboxes values using Salesforce Apex

Sample Code:

Visualforce Page:

<apex:page 
           controller="SampleVisualforcePageController"
           id="pg">
    <apex:form id="frm">
        <apex:messages/>
        <apex:pageblock id="AccountsList" title="Accounts List"  >
            <apex:pageBlocktable value="{!listAccounts}" var="acc" >
                <apex:column title="Select" > 
                    <apex:inputCheckbox value="{!acc.selectedBool}">
                    </apex:inputCheckbox>
                </apex:column>
                <apex:column value="{!acc.objAccount.Name}"/>
            </apex:pageBlocktable>   
            <apex:pageblockButtons >
                <apex:commandButton 
                                    value="Delete" 
                                    action="{!deleteAccounts}" 
                                    reRender="frm"/>
            </apex:pageblockButtons>      
        </apex:pageblock>
    </apex:form> 
</apex:page>

Apex Class:

public class SampleVisualforcePageController {
    
    public List < AccountWrapper > listAccounts { get; set; }
    
    public SampleVisualforcePageController() {
        
        listAccounts = new List < AccountWrapper >();
        
        for ( Account objAccount : [ 
            SELECT Id, Name 
            FROM Account 
            LIMIT 10
        ] ) {
            
            AccountWrapper objWrap = new AccountWrapper();
            objWrap.selectedBool = false;
            objWrap.objAccount = objAccount;
            listAccounts.add(
                objWrap
            );
            
        }
        
    }     
    
    public class AccountWrapper {
        
        public Boolean selectedBool { get; set; }
        public Account objAccount { get; set; }
        
    }
    
    public void deleteAccounts() {
        
        List < AccountWrapper > listTemp = new List < AccountWrapper >();
        List < Account > accountsListToDel = new List < Account >();
        
        for ( AccountWrapper aw : listAccounts ) {
            
            if ( aw.selectedBool ) {
                
                accountsListToDel.add(
                    aw.objAccount
                );

            } else {

                listTemp.add(
                    aw
                );
                            
            }
            
        }
        
        if ( accountsListToDel.size() > 0 ) {
            
            delete accountsListToDel;
            listAccounts = listTemp;
        
        } else {
            
            ApexPages.addMessage(
                new ApexPages.Message(
                    ApexPages.Severity.Error,
                    'Please select atleast one Account'
                )
            );
            
        }
        
    }
    
}

Output:

Leave a Reply