Deleting checked rows using apex in Salesforce?

Sample Code:

Visualforce page:

<apex:page controller="DeletingCheckedRowsController">
<apex:pagemessages />
    <apex:form >
        <apex:pageBlock id="pg">
           <apex:pageBlockTable value="{!listWrapper}" var="w">
               <apex:column > 
                   <apex:facet name="header">
                       <apex:inputCheckbox value="{!allBool}">
                           <apex:actionSupport reRender="pg" action="{!selectAll}" event="onchange"/>
                       </apex:inputCheckbox>
                   </apex:facet>
                   <apex:inputCheckbox value="{!w.checked}"/>
               </apex:column>
               <apex:column value="{!w.emp.Name}"/>
               <apex:column value="{!w.emp.Age__c}"/>
            </apex:pageBlockTable> 
            <apex:pageBlockButtons >
                <apex:commandButton value="Delete" action="{!del}"/>
            </apex:pageBlockButtons>
        </apex:pageBlock>
    </apex:form>
</apex:page>


Controller:

public class DeletingCheckedRowsController {
    public List<WrapperClass> listWrapper {get;set;}
    public Boolean allBool {get;set;}
    
    public DeletingCheckedRowsController() {
        listWrapper = new List<WrapperClass>();
        List<Employee__c> listEmp = [SELECT Id, Name, Age__c FROM Employee__c];
        if(listEmp.size() > 0) {
            for(Employee__c emp : listEmp) {
                listWrapper.add(new WrapperClass(emp));
            }
        }
    }
    
    public class WrapperClass {
        public Boolean checked {get;set;}
        public Employee__c emp {get;set;}
        public WrapperClass(Employee__c emp) {
            this.emp = emp;
        }
    }
    
    public void del() {
        List<Employee__c> listEmpForDel = new List<Employee__c>();
        List<WrapperClass> listTempWrapper = new List<WrapperClass>();
        for(WrapperClass w : listWrapper) {
            if(w.checked) {
                listEmpForDel.add(w.emp);
            } else {
                listTempWrapper.add(w);
            }
        }
        if(listEmpForDel.size() > 0) {
            delete listEmpForDel;
            listWrapper = listTempWrapper;
        } else {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Select atleast one employee to delete'));
        }
    }
    
    public void selectAll() {
        if(allBool) {
            for(WrapperClass w : listWrapper) {
                w.checked = true;
            }
        } else {
            for(WrapperClass w : listWrapper) {
                w.checked = false;
            }
        }
    }
}

Output:



1 comment:

  1. How to check if user user has selected any value or not. If user clicks on delete without selecting anything, i want to display a message saying that please select atleast one item. how to calculate the no. of items selected by user before he clicks delete button. Please advise.

    ReplyDelete