Hello friends, In this tutorial, I'll let you know a working example of a dynamic search in a Visualforce page. The results are shown in a grid with pagination. In this example, there are two fields to filter the data also you can delete multiple records at a time by selecting them using checkbox. So let's start.

Warning: In this example, only those accounts are deleted that are not in a relationship(Lookup's or Master-details) with other salesforce sObject records.

After completing this tutorial you'll able to: 
  • How to create pagination in a Visualforce page?
  • Select record during pagination to delete.
  • How to apply search functionality in pagination? 
So let's get started,

Step 1: Login to your Salesforce Org. and open developer console.

Step 2: Navigate to File | New | Apex Class and create an Apex controller called PaginationCheckboxHandler and replace the following code.

PaginationCheckboxHandler.apxc
 public with sharing class PaginationCheckboxHandler {    
    public Account acc{get;set;}    
    public List<Account> accountList {get;set;}        
    public Integer icount{get;set;}    
    List<string> conditions = new List<string>();    
    private integer totalRecs = 0;    
    private integer OffsetSize = 0;    
    private integer LimitSize= 5;  
    
    //Constructor
    public PaginationCheckboxHandler(){      
        acc = new Account();         
    }
    
    public void searchAcc(){        
        totalRecs = 0;        
        OffsetSize = 0;        
        if(accountList !=null && accountList.size()>0){            
            accountList=null;            
        }        
        searchAccounts ();        
        conditions.clear();        
    }
    
    public Void searchAccounts(){      
        if(accountList != null && !accountList.isEmpty()){            
            accountList.clear();            
        }        
        String strQuery ='SELECT Id,Name,AccountNumber,CreatedDate,Phone,Website,Industry,AnnualRevenue From Account WHERE Id!=null ';           
        if(acc.Name !=null && acc.Name !=''){            
            conditions.add('Name Like \'%' +acc.Name +'%\' ');            
        }        
        if(acc.AccountNumber !=null && acc.AccountNumber !=''){            
            conditions.add('AccountNumber Like\'%' +acc.AccountNumber +'%\' ');            
        }
        if (conditions.size() > 0) {            
            strQuery += ' AND ' + conditions[0];            
            for (Integer i = 1; i < conditions.size(); i++)                
                strQuery += '  AND ' + conditions[i];            
        }
        
        if(totalRecs !=null && totalRecs ==0){            
            System.debug('strQuery>>'+strQuery);            
            List<Account> accTemp = Database.query(strQuery);            
            totalRecs = (accTemp !=null &&accTemp.size()>0)?accTemp.size():0;            
        }
        strQuery += ' ORDER BY Name  ASC, CreatedDate DESC LIMIT :LimitSize OFFSET :OffsetSize';        
        accountList  =Database.query(strQuery);        
    }    
    
    @RemoteAction    
    public static boolean delAccount(String jsonString){        
        boolean flag=false;        
        try{            
            List<String> lstId=(List<String>)JSON.deserialize(jsonString, List<String>.class);            
            System.debug('lstId>>'+lstId);            
            List<Account> lstAccount=new List<Account>();            
            for(String s:lstId){                
                Account a=new Account();                
                a.Id=s; 
                lstAccount.add(a);                
            }            
            if(lstAccount.size()>0){                
                delete lstAccount;                
            }            
            flag=true;            
        }        
        catch(Exception ex){        
        }        
        return flag;        
    }  
    
    public void FirstPage(){        
        OffsetSize = 0;        
        searchAccounts();        
    }
    
    public void previous(){       
        OffsetSize = (OffsetSize-LimitSize);        
        searchAccounts();    
    }
    
    public void next(){        
        OffsetSize = OffsetSize + LimitSize;        
        searchAccounts();        
    }
    
    public void LastPage(){        
        OffsetSize = totalrecs - math.mod(totalRecs,LimitSize);        
        searchAccounts();        
    }
    
    public boolean getprev(){        
        if(OffsetSize == 0){         
            return true;          
        }        
        else {      
            return false;         
        }        
    }
    
    public boolean getnxt(){        
        if((OffsetSize + LimitSize) > totalRecs){            
            return true;           
        }        
        else { 
            return false;            
        }        
    }    
 }

Step 3: Navigate to File | New | Visualforce Page and create a new Visualforce Page called PaginationWithoutCheckbox and replace the following markup.

PaginationWithoutCheckbox.vfp
 <apex:page controller="PaginationCheckboxHandler" action="{!searchAcc}" sidebar="false" showHeader="false">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
    <script type="text/javascript">
        window.onload=function() {
        // document.getElementById("{!$Component.thePb.thepbs.accName}").focus();
    }
    </script>
    <apex:form>        
        <apex:pageBlock id="thePb" title="Account Details To Search">            
            <apex:pageblockSection id="thepbs">                
                <apex:inputField value="{!acc.Name}" required="false" id="accName"/>                
                <apex:inputfield value="{!acc.accountNumber}"/>                
            </apex:pageblockSection>            
            <apex:pageblockButtons location="bottom" id="thepbb">                
                <apex:commandButton value="Search" action="{!searchAcc}" id="btnSearch" />                
                <apex:commandButton value="Deleted" onclick="getSelected()" rerender="thePb"/>                
            </apex:pageblockButtons>            
        </apex:pageBlock>  
        <apex:pageBlock title="Account Details" id="noRec" rendered="{! IF( accountList != null && accountList.size ==0 , true, false)}" >            
            <apex:outputPanel >                
                <h1>No Records Found </h1>                
            </apex:outputPanel>            
        </apex:pageBlock>
        <apex:pageBlock title="Account Details" id="details" rendered="{! IF( accountList != null && accountList.size >0, true, false)}" >            
            <table width="100%" id="tbl">                
                <tr>                    
                    <td><input type="checkbox" id="selectAll" onclick="selectAllCheckboxes(this,'inputId')"/></td>                    
                    <!--<td></td>-->                    
                    <td>Name</td>                    
                    <td>Account Number</td>                    
                    <td>Industry</td>                    
                    <td>Phone</td>                    
                </tr>                
                <tbody id="tblbody">                    
                    <apex:repeat value="{!accountList}" var="a">                        
                        <tr>                            
                            <td> <input type="checkbox" value="{!a.Id}" id="inputId"/></td>                            
                            <!--<td><a href="#" onclick="return reject('{!a.Id}')">Reject</a></td>-->                            
                            <td><apex:outputLink target="_blank" value="/{!a.id}">{!a.Name}</apex:outputLink></td>                            
                            <td>{!a.accountNumber}</td>                            
                            <td>{!a.Industry}</td>                            
                            <td>{!a.Phone}</td>                            
                        </tr>                        
                    </apex:repeat>                    
                </tbody>                
            </table>
            <apex:pageblockButtons >                
                <apex:commandButton value="First Page" rerender="details" action="{!FirstPage}" disabled="{!prev}" oncomplete="uncheck()" />                
                <apex:commandButton value="Previous" rerender="details" action="{!previous}" disabled="{!prev}" oncomplete="uncheck()"/>                
                <apex:commandButton value="Next" rerender="details" action="{!next}" disabled="{!nxt}" oncomplete="uncheck()"/>                
                <apex:commandButton value="Last Page" rerender="details" action="{!LastPage}" disabled="{!nxt}" oncomplete="uncheck()"/>                
            </apex:pageblockButtons>
        </apex:pageBlock>        
        <script>        
        function uncheck(){            
            document.getElementById('selectAll').checked=false;            
        }
        
        function selectAllCheckboxes(obj,receivedInputID){            
            var inputCheckBox = document.getElementsByTagName("input");      
            for(var i=0; i<inputCheckBox.length; i++){          
                if(inputCheckBox[i].id.indexOf(receivedInputID)!=-1){                  
                    inputCheckBox[i].checked = obj.checked;                    
                }                
            }            
        }        
        
        function getSelected(){            
            var ids=[];            
            $('#tblbody').find('input[type="checkbox"]:checked').each(function () {                
                ids.push($(this).val());
                
            });            
            if(ids.length>0){                
                var idsstring=JSON.stringify(ids);               
                PaginationCheckboxHandler.delAccount(idsstring,function(result,event){                    
                    if(event.status){                        
                        if(result){                            
                            document.getElementById("{!$Component.thePb.thepbb.btnSearch}").click();                            
                        }                        
                        else{                            
                            alert('Record is related with other records');                            
                        }                        
                    }                    
                });                
            }            
        }        
        function reject(Id){            
            alert(Id);   
        }
        </script> 
    </apex:form>
 </apex:page>

Output:

See also:

Conclusion:
Hope you like this tutorial, for any query or suggestions please feel free to comment.
Thank you.