1

I have a requirement to do sorting. I did it with sort() but does only in ascending way. My client wants to have column sorting, how can I do this with my code?

public class PagingTasksController{

public List<Task> tasks;
public Integer CountTotalRecords{get;set;}
public String QueryString {get;set;}
public Integer OffsetSize = 0;
private Integer QueryLimit = 3;
public List<Task> lstTasks;
public String searchText {get;set;} 

public PagingTasksController (){
    //CountTotalRecords= [select count() from Task];
}



public List<Task> getTasks(){
    if(tasks == null){
        tasks = new List<Task>();
    }
    return tasks;
}

public void findTasks(){
    String qStr2 = 'Select count() from Task where Subject like \'%'+searchText+'%\' OR Status like \'%'+searchText+'%\'';
    CountTotalRecords = Database.countQuery(qStr2);
    queryTasks();
}

public void  queryTasks(){
    String qStr = 'Select OwnerId,Subject,Status,Priority from Task where Subject like \'%'+searchText+'%\' OR Status like \'%'+searchText+'%\' Order By Subject,Status limit ' + QueryLimit + ' offset ' + OffsetSize;
    tasks = Database.query(qStr);
    tasks.sort();

}

public Boolean getDisablePrevious(){
    if(OffsetSize>0){
        return false;
    }
    else return true;
}

public Boolean getDisableNext() {
    if (OffsetSize + QueryLimit < countTotalRecords){
        return false;
    }
    else return true;
}

public PageReference Next() {
    OffsetSize += QueryLimit;
    queryTasks();
    return null;
}

public PageReference Previous() {
    OffsetSize -= QueryLimit;
    queryTasks();
    return null;
}

  public PageReference save() {
    update tasks;
    return ApexPages.CurrentPage();
 }

}

Page:

<apex:page controller="PagingTasksController">
<apex:form >
    <apex:pageBlock title="Tasks" id="pgBlock">
       <apex:pageBlockButtons >
           <apex:commandButton action="{!save}" id="saveButton" value="Save"/>
           <apex:commandButton onclick="resetInlineEdit()" id="cancelButton" value="Cancel"/>
       </apex:pageBlockButtons>

    <apex:inlineEditSupport showOnEdit="saveButton, cancelButton"
                hideOnEdit="editButton" event="ondblclick"
                changedStyleClass="myBoldClass" resetFunction="resetInlineEdit"/>

     <apex:inputText id="searchBox" value="{!searchText}"/>
    <apex:commandButton value="Search" reRender="pgTable,pgBlock" action="{!findTasks}"/>
      <apex:pageBlockTable value="{!Tasks}" var="tsk" id="pgTable" >
       <apex:column >
        <apex:outputLink value="{!URLFOR($Action.Task.Delete, tsk.id,['retURL'='/apex/Task_Assignment_Features'])}" >Delete</apex:outputLink>
</apex:column>

      <apex:column headerValue="Subject">
        <apex:outputField value="{!tsk.Subject}"/>
       </apex:column>
       <apex:column headerValue="Status">
         <apex:outputField value="{!tsk.Status}"/>
     </apex:column>
     <apex:column headerValue="Priority">
        <apex:outputField value="{!tsk.Priority}"/>
    </apex:column>
    <apex:column headerValue="OwnerId">
        <apex:outputField value="{!tsk.OwnerId}"/>
    </apex:column>
 </apex:pageBlockTable>
   <apex:pageBlockButtons >
            <apex:commandButton value="Previous" action="{!Previous}" rerender="pgTable,pgBlock"
                                status="status" disabled="{!DisablePrevious}" />
            <apex:commandButton value="Next" action="{!Next}" reRender="pgTable,pgBlock"
                                status="status" disabled="{!DisableNext}" />
            <apex:actionStatus id="status" startText="Please Wait..."/>
        </apex:pageBlockButtons>
    </apex:pageBlock>
</apex:form>
 <apex:enhancedlist type="Activity" height="800" rowsPerPage="50" customizable="False"/>

4
  • It is usually simplest to add an "order by" term to the SOQL with an "asc" or "desc" suffix for the direction rather than going the sorting in Apex. If you Google you will find many examples.
    – Keith C
    Commented Jul 20, 2014 at 13:56
  • Keith, The requirement is to have an arrow column sorting which i seem will work with Jquery.I'm stucked here.
    – JJoseph
    Commented Jul 20, 2014 at 13:59
  • 4
    You do not need to use jQuery at all: you can add an apex:commandLink to the column heading and get your controller to do the work and then re-render. Here is one example of that: A Recipe for Column Sorting. Client-side sorting (e.g. jQuery DataTables) is most effective when all the data can be queried at once so that all the work can be done at the client side.
    – Keith C
    Commented Jul 20, 2014 at 15:19
  • 1
    Adding "please help," "this is urgent," etc is implicit in your question.
    – Adrian Larson
    Commented Dec 29, 2015 at 14:52

2 Answers 2

2

Here is a very simple example of how you could implement sorting using some visualforce and apex. The trick here is an apex:facet tag, where you can set a link with some parameters. In this case it is a sort field name and the sort order. Every time a user clicks on the header link - the pageBlockTable is re-rendered with new attributes for the sort field and order:

Apex Class:

public class myClass{

    public String sortField {get;set;}
    public String myOrder {get;set;}
    public myClass(){
        // Default setting for the sorting
        sortField = 'CreatedDate';
        myOrder = 'DESC';
    }

    public List<Contact> getContacts(){

        String q = 'Select Id, FirstName, LastName From Contact ';
        q += ' Order by ' +  String.escapeSingleQuotes(sortField) + ' ' + myOrder + ' LIMIT 10';
        return Database.query(q);
    }
}

Visualforce Page:

<apex:pageBlock>
<apex:pageBlockTable value="{!contacts}" var="con" id="myTable">
    <apex:column>
        <apex:facet name="header">
            <apex:commandLink value="FirstName" reRender="myTable">
                <apex:param name="sortField" value="FirstName" assignTo="{!sortField}" />
                <apex:param name="myOrder" value="{!IF(myOrder == 'DESC', 'ASC','DESC')}" assignTo="{!myOrder}" />
                First Name
            </apex:commandLink>
        </apex:facet>
        <apex:outputField value="{!con.FirstName}" />
    </apex:column>
    <apex:column>
        <apex:facet name="header">
            <apex:commandLink value="LastName" reRender="myTable">
                <apex:param name="sortField" value="LastName" assignTo="{!sortField}" />
                <apex:param name="myOrder" value="{!IF(myOrder == 'DESC', 'ASC','DESC')}" assignTo="{!myOrder}" />
                Last Name
            </apex:commandLink>
        </apex:facet>
        <apex:outputField value="{!con.LastName}" />
    </apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
0

The simplest way to solve this is to execute soql with 'ASC'/'DESC', you can add arrow for each column and execute 'Order by sorting column ASC/DESC' when the column is clicked.

1
  • Could you please suggest me an example for this ? I did not get you here.
    – JJoseph
    Commented Jul 20, 2014 at 14:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .