function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ShaikAShaikA 

How to implement sorting functionality for dynamic columns in a pageblocktable

HI,

Please any one help me with code to implement the sorting functionality for dynamic colums in a table.

<apex:pageblock id="recds" >
                                    <apex:pageblockTable value="{!selectedObjreport}" var="r" id="theaddrs" rendered="{!IF(selectedObjreport.size!=0 , true , false)}">
                      <apex:repeat value="{!selectedObjFields}" var="FieldLable" id="repeat" >  
                       <apex:column >
                <apex:facet name="header">
                    <apex:commandLink value="{!r[FieldLable]}" action="{!toggleSort}" rerender="results,debug">
                        <apex:param name="sortField" value="{!r[FieldLable]}" assignTo="{!sortField}"/>
                    </apex:commandLink>
                </apex:facet>
                <apex:outputField value="{!r[FieldLable]}" rendered="{!IF(FieldLable != '--None--' , true, false)}"/>
            </apex:column>                                         
       </apex:repeat>
  </apex:pageblockTable>                      
</apex:pageblock>

Regards,
Anand
Michael WelburnMichael Welburn
We'll need a little more information to see where you are stuck.
  • Are you seeing the toggleSort() method getting called when you click on the column header?
  • Are you re-executing the query with the new sort parameter set?
  • Is the component being refreshed after toggleSort() runs? (have you specified the right IDs for rerender)
ShaikAShaikA
Hi Michael,

Please find the below code, help me to know what i am missing here.

VF Page:

<apex:page controller="ReportClass" id="page">
<style>
table, th, td {
    border: 1px solid black;
     color:blue;
     text-align: center;
     text-size: 15;
}


#table_container1{width:70%;margin:0 auto;}
</style>
<script>
    function myJavascriptFunc()
    {        
CallApexMethod() ;
       }
    
    function reportFunc()
    {        

        CallReport() ;
       
    }
    
</script>
<apex:form id="frm">
    <apex:actionFunction name="CallApexMethod" action="{!fetchFields}" reRender="flds,theaddrs,repeat" />
    <!--<apex:actionFunction name="CallReport" action="{!report}" reRender="recds,pbtable,repeat" />-->
    <apex:pageBlock >
        <table style="width:100%">
            <th >Filter Criteria</th>
            <apex:panelgrid columns="2">
                <apex:panelgroup >
                    <table style="float:left;width:30%">
                        <th> Fields </th>
                        <tr><td>
                            <Label>Object</label>&nbsp;
                            <apex:SelectList value="{!objectList}" size="1" onchange="myJavascriptFunc()" id="select" >
                            <apex:selectOption itemLabel="--None--" itemValue="--None--" />
                            <apex:selectOptions value="{!objName}" ></apex:selectOptions>
                            </apex:SelectList>
                        </td></tr>
                        <tr><td>
                            <apex:pageblock id="flds" >
                                <apex:pageblockTable value="{!selectedObjFields}" var="fields" >
                                    <apex:column value="{!fields}" />
                                </apex:pageblockTable>
                            </apex:pageblock>    
                        </td></tr>
                    </table>
                </apex:panelgroup>
                <apex:panelgroup >
                    <table style="float:left;width:70%">
                        <th> Report </th>
                            <tr><td>  
                                <apex:pageblock id="recds" >
                                    <apex:pageblockTable value="{!selectedObjreport}" var="r" id="theaddrs" rendered="{!IF(selectedObjreport.size!=0 , true , false)}">
                                            <apex:column value="{!r.id}" rendered="{!IF(selectedObjFields.size == 0 , true, false)}"/>
                                    <apex:repeat value="{!selectedObjFields}" var="FieldLable" id="repeat" >  
                                      <apex:column >
                                        <apex:facet name="header">
                                            <apex:commandLink value="{!FieldLable}" action="{!toggleSort}" rerender="recds,theaddrs">
                                                <apex:param name="sortField" value="{!FieldLable}" assignTo="{!sortField}"/>
                                            </apex:commandLink>
                                        </apex:facet>
                                        <apex:outputField value="{!r[FieldLable]}" rendered="{!IF(FieldLable != '--None--' , true, false)}"/>
                                     </apex:column>
                                  </apex:repeat>
                              </apex:pageblockTable>                       
                                </apex:pageblock>
                             </td></tr>
                        </table>
                </apex:panelgroup>
             </apex:panelgrid>      
        </table>
    </apex:pageBlock>
</apex:form>
</apex:page>

Class:

public with sharing class ReportClass {
public String myQuery {get;set;}
public string objectList{get;set;}
public List<String> selectedObjFields{get;set;}
public List<sObject> selectedObjreport{get;set;}
public List<String> sFields{get;set;}
    public String getobjectList()
    {
        return objectList;
       
    }
    public void setobjectList()
    {
        this.objectList = objectList;
        System.debug('Selected Object is objectList>>>>2222' + objectList);
    }
   /* public String getobjName()
    {
        return objName;
    }*/
    
    public ReportClass (){
    
    }
    
    public List<SelectOption> getobjName()
    {

        List<Schema.SObjectType> gd = Schema.getGlobalDescribe().Values();    
        List<SelectOption> options = new List<SelectOption>();

        for(Schema.SObjectType f : gd)
        {
           options.add(new SelectOption(f.getDescribe().getName(),f.getDescribe().getName()));
        }
        return options;
    }

    public void fetchFields()
    {
       List<String> fields = new List<String>();
       Map<String , Schema.SObjectType> globalDescription = Schema.getGlobalDescribe();
            System.debug('Selected Object is objectList>>>>' + objectList);
            Schema.sObjectType objType = globalDescription.get(objectList);
            System.debug('Object Type is objType>>>>' + objType);
            Schema.DescribeSObjectResult r1 = objType.getDescribe();
            System.debug('Object Type is r1>>>>> ' + r1);
            Map<String , Schema.SObjectField> mapFieldList = r1.fields.getMap();  
        if(objectList!= '--None--')  
        {  
            for(Schema.SObjectField field : mapFieldList.values())  
            {  
                Schema.DescribeFieldResult fieldResult = field.getDescribe();
                
                
               if(fieldResult.isAccessible())  
               {  
                 if(string.valueof(fieldResult.getName())!='id'&& string.valueof(fieldResult.getName())!='SystemModstamp' && string.valueof(fieldResult.getName())!='ownerid' && string.valueof(fieldResult.getName())!='IsDeleted' && string.valueof(fieldResult.getName())!='deleted' && string.valueof(fieldResult.getName())!='LastActivityDate' && string.valueof(fieldResult.getName())!='LastModifiedDate' && string.valueof(fieldResult.getName())!='LastModifiedById' && string.valueof(fieldResult.getName())!= 'LastViewedDate' && string.valueof(fieldResult.getName())!='LastReferencedDate')
                 {
                   // if(!fieldResult.endsWith('id')){
                    System.debug('Field Name is ' + fieldResult.getName());
                    fields.add(fieldResult.getName());
                 }
               }  
            }
                List<String> so = new List<String>();
                for(String f : fields)
                {
                    so.add(f);
                }
                selectedObjFields= so;   
            
                    if(selectedObjFields !=null)
                   {
                        String myQuery = 'Select Id ' ;  
                        for(String field : selectedObjFields)  
                        {  
                            if(field.toLowerCase() != 'id')  
                            myQuery += ','+ field + ' ' ;  
                        }  
                        System.debug('>>>>>> sFields: ' + sFields);
                        //Limit is 100 for now you can change it according to need  
                        myQuery += ' from ' + objectList+ ' LIMIT 10' ;  
                        //Executing the query and fetching results  
                        selectedObjreport= Database.query(myQuery) ;  
                    }
        }
    }
    
    //======================sorting================
    public String sortDir {
    get  { if (sortDir == null) {  sortDir = 'asc'; } return sortDir;  }
    set;
  }

  // the current field to sort by. defaults to last name
  public String sortField {
 
    get  { if (sortField == null) {sortField = 'name'; } return sortField;  }
    set;
    
  }
      // format the soql for display on the visualforce page
  public String debugSoql {
    get { return myQuery + ' order by ' + sortField + ' ' + sortDir + ' limit 20'; }
    set;
  }

    public void toggleSort() {
    // simply toggle the direction
    sortDir = sortDir.equals('asc') ? 'desc' : 'asc';
    // run the query again
    runQuery();
  }

  // runs the actual query
  public void runQuery() {

    try {
      selectedObjreport= Database.query(myQuery + ' order by ' + sortField + ' ' + sortDir + ' limit 10');
    } catch (Exception e) {
      ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Ooops!'));
    }

  }

}
Michael WelburnMichael Welburn
I'm still not quite sure where you are stuck, it could be a number of places. You'll need to isolate what isn't working (using the bullets mentioned in my previous post) to help hone in on what you need to fix.

At minimum, your rerender attribute appears to point to IDs that don't exist on your page. I suggest changing from rerender="results,debug" to rerender="recds", although that implies the rest of your logic is being invoked and functioning correctly, and that your only issue is that the page was not refreshing.