0

We have a visualforce page and it have 35 pages and in each page we are showing 100 or 200 records. By clicking the next button we are moving to the next set of records. But here the issue is we are sorting the list of records for only one page but if we are moving to the next page again it is showing sorting details from A-Z. Instead of sorting applying at each page we need sorting functionality for the complete 35 pages.

Request : If we click on Account Name in first page we need all 1 to 35 pages should apply sorting (A-Z OR Z-A).

Visualforce page :

<apex:page id="mainPage" controller="ListViewEdit" sidebar="false" >
    <apex:form id="pageForm">
        <apex:outputPanel id="errorPanel" >
            <apex:pageMessages id="error" />  
        </apex:outputPanel>
        <apex:outputText value="<b>Available List Views for Contacts : </b>" escape="false" />      
        <apex:selectList value="{!filterId}" size="1" id="filterMenu">
            <apex:selectOptions value="{!ContactExistingViews}"></apex:selectOptions>
            <apex:actionSupport event="onchange"  action="{!resetFilter}"  status="ajaxStatus"/> <!-- rerender="pageBlk,errorPanel"  -->
        </apex:selectList>
        &nbsp;&nbsp;
        <apex:commandButton value="Reload" action="{!resetFilter}" rerender="pageBlk,errorPanel" status="ajaxStatus" />
        &nbsp;&nbsp;
        <b>Records Per Page:</b>&nbsp; <apex:selectList value="{!pageSize}" id="pageSize" size="1"  >
            <apex:selectOption itemValue="100" itemLabel="100"  />
            <apex:selectOption itemValue="200" itemLabel="200" />
            <apex:actionSupport event="onchange"  action="{!resetFilter}"  status="ajaxStatus"/>  <!-- rerender="pageBlk,errorPanel" -->
        </apex:selectList>
        &nbsp;&nbsp;
        <!--    <apex:actionStatus id="ajaxStatus" startText="Loading..."  stopText=""/>    -->
        <apex:outputPanel >                      
            <apex:actionStatus id="ajaxStatus" >
                <apex:facet name="start" >
                    <img src="/img/loading.gif" />                    
                </apex:facet>
            </apex:actionStatus>
        </apex:outputPanel>
        <apex:outputPanel >                      
            <apex:actionStatus id="sortStatus" >
                <apex:facet name="start" >
                    <img src="/img/loading.gif" />   
                </apex:facet>
            </apex:actionStatus>
        </apex:outputPanel> 
        <br/><br/>
        <apex:pageBlock id="pageBlk" title="Contacts">
            <apex:pageBlockButtons style="float:center" id="pageBlkBtnsPanel" >
                <b>
                    <i><apex:outputText value="Important:" style="color:red;" /></i>
                    <apex:outputText value=" After making your changes click <u>here</u> and then SAVE " escape="false" /> 
                </b> 
                <apex:commandButton value="Save Contacts" action="{!save}" id="saveButton" status="ajaxSaveStatus"  /> <!-- reRender="pageBlk,errorPanel"  -->
                <apex:outputPanel >                      
                    <apex:actionStatus id="ajaxSaveStatus" >
                        <apex:facet name="start" >
                            <img src="/img/loading.gif" />                    
                        </apex:facet>
                    </apex:actionStatus>
                </apex:outputPanel> 
                <apex:outputPanel style="float:right" id="buttonsPanel" >  
                    <apex:outputText value="Page {!setController.pageNumber} of {!CEILING(setController.resultSize/setController.pageSize)}" rendered="{!setController.resultSize > 0}" />
                    <apex:outputText value="Page {!setController.pageNumber} of {!setController.pageNumber}" rendered="{!setController.resultSize <= 0}" />
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <apex:commandButton action="{!firstPage}" value="First"  status="ajaxStatus" /><!-- reRender="pageBlk,errorPanel"  -->
                    <apex:commandButton action="{!prev}" value="Prev"   disabled="{!!setController.hasPrevious}"  status="ajaxStatus" /><!-- reRender="pageBlk,errorPanel"  -->
                    &nbsp;&nbsp;&nbsp;&nbsp;
                    <apex:commandButton action="{!next}" value="Next"  disabled="{!!setController.hasNext}"  status="ajaxStatus" /><!--  reRender="pageBlk,errorPanel" -->
                    <apex:commandButton action="{!lastPage}" value="Last"  status="ajaxStatus" /><!-- reRender="pageBlk,errorPanel"  -->
                </apex:outputPanel>
            </apex:pageBlockButtons>
            <apex:pageBlockTable value="{!Contacts}" var="record" id="ConTable" width="100%" >
                <apex:column >
                    <apex:facet name="header">   
                        <apex:commandLink status="sortStatus" action="{!dummy}" value="Account Name {!IF(ExpressionSort=='Account',IF(DirectionOfSort == 'ASC', '▼', '▲'),'')}"  >
                            <apex:param value="Account" name="column" assignTo="{!ExpressionSort}" ></apex:param>
                        </apex:commandLink> 
                    </apex:facet>
                </apex:column> 
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Apex Class :

public with sharing class ListViewEdit {
    
    private String baseQuery = 'SELECT Id,Name,FirstName,LastName,ZTS_US_Profession__c,ZTS_US_Job_Function__c,
                               title,AccountId,Email,ZTS_EU_Contact_Status__c,MobilePhone,Phone,OwnerId,Interface_Email__c,
                               Account.Name,LastModifiedById,ZTS_US_Account_influence__c,Account.ZTS_US_Business_Class__c,Account.ZTS_US_LE_Account__c 
                               FROM Contact WHERE ZTS_EU_Market__c = \'United States\' limit 10000';
    
    public String filterId {get; set;}
    //@TestVisible  private Integer pageSize1 = 200;
    public boolean modFlag {get;set;}
    private static String MODIFIED_ROWS_MSG = 'Contact records have been modified! Please remember to press the Save Contacts button to save all changes before moving to the next page. If you press the Reload button, it will clear all changes made in the contact edit list view.';
    private static String DEFAULT_LV_SELCTION_APINAME = 'My_Pending_First_or_Last_Name';
    public String SortingExpression = 'Account';
    public String DirectionOfSort = 'ASC';
    public Integer pageSize {get;set;}
    
    public ListViewEdit(){}
    
    public ApexPages.StandardSetController setController {
        get{
            if(setController == null){
                setController = new ApexPages.StandardSetController(Database.getQueryLocator(baseQuery));
                pageSize = pageSize == null ? 100 : pageSize;
                setController.setPageSize(pageSize);                
                // We have to set FilterId after Pagesize, else it will not work
                if(filterId != null) {
                    setController.setFilterId(filterId);
                }else{
                    List<System.SelectOption> lvs = setController.getListViewOptions();
                    boolean flag = false;
                    if(lvs != null && !lvs.isEmpty()){
                        for(System.SelectOption so : lvs){
                            if(so.getLabel() == 'Recently Viewed Contacts'){
                                filterId = so.getValue(); 
                                flag = true;
                                break;
                            }
                        }
                        if(!flag){
                            filterId = (lvs[0]).getValue();                                                    
                        }
                        setController.setFilterId(filterId);
                    }
                }
                setController.setPageNumber(1);
            }
            return setController;
        }set;
    }
    
    public ListViewEdit(ApexPages.StandardSetController c) {   }
    
    //Navigate to first Page
    public void firstPage()
    {
        try{
            setController.first(); 
        }catch(Exception ex){
            ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.WARNING, MODIFIED_ROWS_MSG));
            modFlag = true;
            System.debug('..modFlag in previous..' + modFlag);
        }        
    }
    
    //Navigate to last Page
    public void lastPage()
    {
        try{
            setController.last();
        }catch(Exception ex){
            ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.WARNING, MODIFIED_ROWS_MSG));
            modFlag = true;
            System.debug('..modFlag in previous..' + modFlag);
        }         
    }
    
    //Navigate to Next page
    public void next()
    {
        if(setController.getHasNext())
        {
            try{
                setController.next();
                System.debug('...next...' + setController.getPageNumber());
            }catch(Exception ex){
                ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.WARNING, MODIFIED_ROWS_MSG));
                modFlag = true;
                System.debug('..modFlag in previous..' + modFlag);
            }         
        }
    }
    
    //Navigate to Prev Page
    public void prev()
    {
        if(setController.getHasPrevious())
        {
            try{
                setController.previous();
            }catch(Exception ex){
                ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.WARNING, MODIFIED_ROWS_MSG));
                modFlag = true;
                System.debug('..modFlag in previous..' + modFlag);
            }            
        }
    }
    
    public String ExpressionSort {
        get {
            return SortingExpression;
        }
        set {
            If(value == SortingExpression) {
                DirectionOfSort = (DirectionOfSort == 'ASC')? 'DESC' : 'ASC';
            }
            else {
                DirectionOfSort = 'ASC';
                SortingExpression = value;
            }
        }
        
    }
    
    public String getDirectionOfSort() {
        If(SortingExpression == Null || SortingExpression == '') {
            return 'DESC';
        }
        else {
            return DirectionOfSort;
        }
    }
    
    public void setDirectionOfSort(String value) {
        DirectionOfSort = value;
    }
    
    public void dummy(){
        
    }
    
    public List<Contact> getContacts()
    {
        List<Contact> sortedRecs = new List<Contact>();
        List<ContactWrapper> contWrapList = new List<ContactWrapper>();
        List<Contact> conts = setController.getRecords();
        for(Contact c : conts){
            contWrapList.add(new ContactWrapper(c,this));
        }
        contWrapList.sort();
        for(ContactWrapper cw : contWrapList){
            sortedRecs.add(cw.cont);
        }
        return sortedRecs;
    }
    
    //Get all available list view for Contact
    public SelectOption[] getContactExistingViews(){
        return setController.getListViewOptions();
    }
    
    public PageReference resetFilter()
    {
        setController = null;
        //setController.setPageNumber(1);
        modFlag = false;
        return null;
    }
    
    public System.PageReference save(){
        Integer pageNo = setController.getPageNumber();
        setController.save();
        setController.setPageNumber(pageNo);
        modFlag = false;
        return null;
    }
    
    
    public class ContactWrapper implements Comparable {
        
        public Contact cont; 
        public ListViewEdit outerC;
        
        public ContactWrapper(Contact con, ListViewEdit outerC) {
            cont = con;
            this.outerC = outerC;
        }
         
        public Integer compareTo(Object compareTo) { 
            ContactWrapper compareToCont = (ContactWrapper)compareTo;
             
            Integer returnValue = 0;
            if    ((outerC.SortingExpression == 'Account' && cont.Account.Name > compareToCont.cont.Account.Name))
            { 
                returnValue = outerC.DirectionofSort == 'ASC' ? 1 : -1 ;
                
            } else if ( (outerC.SortingExpression == 'Account' && cont.Account.Name < compareToCont.cont.Account.Name))
            { 
                returnValue = outerC.DirectionofSort == 'ASC' ? -1 : 1 ;
            }
            return returnValue;       
        }
    } 
}

Kindly please help how to modify existing logic as per the request.

3
  • 1
    Seems likely related to how you try to manage the standard controller.
    – Phil W
    Jan 23, 2022 at 16:56
  • What have you tried? Where are you stuck? Salesforce Stack Exchange is not a code writing service, but we're happy to help once you make an attempt and encounter a specific problem.
    – David Reed
    Jan 23, 2022 at 17:55
  • Keep the same standard controller instance through the entire lifecycle and make sure you update it when state (e.g. sorting) changes.
    – Phil W
    Jan 30, 2022 at 15:30

0

You must log in to answer this question.

Browse other questions tagged .