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
Thakkar ParthThakkar Parth 

sorting on date gives me error

I've an issue while sorting date by arrow sorting. I successfully implemented this for "Subject" and "Status" field on Task object but while i click on Date column , it gives me error saying : unexpected token: <EOF> Error is in expression '{!toggleSort}' in page new_test_task_assignment: Class.PagingTasksController1.toggleSort: line 61, column 1

I've given endless try but still the same . Can anyone please help me to correct my mistake(s) .. Please help .

Thanks in advance.
 Marc   

public class PagingTasksController1{
    
    public List<Task> tasks {get;set;}
    public Task del;
    public Task taskDel;
    public Integer CountTotalRecords{get;set;}
    public String QueryString {get;set;}
    public Integer OffsetSize = 0;
    private Integer QueryLimit =3 ;
    public List<Task> lstTasks {get;set;}
    public String searchText {get;set;}
    public String rowIndex {get;set;}
    public Date mydate;
    public Integer totalCount {get;set;}
    public string sortField = 'Subject';  // default sort column
    private string sApplySOQL = '';
    public List<Task> delattendeeList {get;set;}
    
    public List<Task> delAttendees {get; set;}
    
    public PagingTasksController1(ApexPages.StandardController controller) {
        
        taskDel= (Task)controller.getRecord();
        tasks = [Select id,Subject,Status,ActivityDate,Owner.Name from Task];
        // this.Tasks=Tasks[0];
        totalCount = Tasks.size();
        
        delattendeeList = new List<Task>();
        delattendees = new List<Task>();
    }
    
    
    // the current sort direction. defaults to ascending
    public String sortDir {
        get  { if (sortDir == null) {  sortDir = 'asc'; } return sortDir;  }
        set;
    }
    
    // the current field to sort by. defaults to role name
    public String getsortField() {
        return sortField;
    }
    
    // the current field to sort by.
    public void setsortField(string value) {
        sortField = value;
    }
    
    // toggles the sorting of query from asc<-->desc
    public void toggleSort() {
        // simply toggle the direction
        sortDir = sortDir.equals('asc') ? 'desc' : 'asc';
        
        integer iIndex = sApplySOQL.indexOf('Order By');
        if (iIndex > -1){
            sApplySOQL = sApplySOQL.substringBefore('Order By');
            sApplySOQL = sApplySOQL + ' Order By ' + sortField + ' ' + sortDir +  ' limit ' + QueryLimit + ' offset ' + OffsetSize;
        }
        
         System.debug('Before Sorted Date is ' +sApplySOQL);
         tasks = Database.query(sApplySOQL );  // here it where gives me error
         
    }
       
    public PagingTasksController1 (){
        //CountTotalRecords= [select count() from Task];
        //String qStr2= '7/23/2014';
        
    }
    
    /* 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 qStr2= searchText;
        String strnormal = '';
        try{
            mydate = date.parse(qStr2);
        }catch(Exception e)
        { }
        
        String strDate = '';
        if(mydate != null) {
            // strnormal = String.valueOf(mydate );
            String[] qstr3 = String.valueOf(mydate).split(' ',2);
            strDate = ' ActivityDate =  '+ qstr3[0] + ' ';
        }else{
            
            strDate  =  '(Subject like \'%'+searchText +'%\' OR Status like \'%' +searchText+ '%\' OR Owner.Name like \'%' +searchText+ '%\') ' + ' Order By '  + sortField;
        }
        
        String qStr = 'Select Owner.Name,Subject,Status,ActivityDate from Task where '+strDate+' limit ' + QueryLimit + ' offset ' + OffsetSize;
        System.debug(qStr);
        tasks = Database.query(qStr);
        
    }
    
    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();
    }
    
    public void deleteRow(){
        delete new Task(Id = rowIndex);
        for (Integer i = 0; i < Tasks.size(); i++) {
            if (Tasks[i].Id == rowIndex) {
                Tasks.remove(i);
                break;
            }
        }
    }
}

====== Page =====

<apex:page controller="PagingTasksController1" docType="html-5.0">
    <apex:form >
     <apex:variable var="rowNumber" value="{!0}"/>
        <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 headerValue="Action" >
              <apex:commandButton value="Delete" action="{!deleteRow}" reRender="pgTable"> 
                 <apex:param name="rowIndex" value="{!tsk.id}" assignTo="{!rowIndex}" />
              </apex:commandButton>              
           </apex:column> 
           
        <!-- <apex:column headerValue="Action" >
          <apex:outputLink value="{!URLFOR($Action.Task.Delete, .id,['retURL'='/apex/New_Test_task_Assignment'])}"> Delete</apex:outputLink>
        </apex:column>  -->
        <apex:column headerValue="Subject">
            <apex:facet name="header">
                <apex:commandLink value="Subject" action="{!toggleSort}" rerender="pgTable" >
                  <apex:param name="sortField" value="Subject" assignTo="{!sortField}"/>
                    <apex:outputPanel rendered="{!BEGINS(sortField,'Subject')}">
                        &nbsp;<apex:image value="{!IF(sortDir = 'desc','/img/arrowDown.gif','/img/arrowUp.gif')}"/>
                    </apex:outputPanel>
                </apex:commandLink>
            </apex:facet>     
          <apex:outputField value="{!tsk.Subject}"/>
        </apex:column>
           
        <apex:column headerValue="Status">
            <apex:facet name="header">
                <apex:commandLink value="Status" action="{!toggleSort}" rerender="pgTable" >
                      <apex:param name="sortField" value="Status" assignTo="{!sortField}"/>
                        <apex:outputPanel rendered="{!BEGINS(sortField,'Status')}">
                          &nbsp;<apex:image value="{!IF(sortDir = 'desc','/img/arrowDown.gif','/img/arrowUp.gif')}"/>
                        </apex:outputPanel>
                </apex:commandLink>
            </apex:facet>         
            <apex:outputField value="{!tsk.Status}"/>
        </apex:column>
       
        <apex:column headerValue="Assigned To">
            <apex:outputField value="{!tsk.Owner.Name}"/>
        </apex:column>
        
       <apex:column headerValue="Due Date">
          <apex:facet name="header">
                <apex:commandLink value="ActivityDate" action="{!toggleSort}" rerender="pgTable" >
                      <apex:param name="sortField" value="ActivityDate" assignTo="{!sortField}"/>
                        <apex:outputPanel rendered="{!BEGINS(sortField,'ActivityDate')}">
                          &nbsp;<apex:image value="{!IF(sortDir = 'desc','/img/arrowDown.gif','/img/arrowUp.gif')}"/>
                        </apex:outputPanel>
                </apex:commandLink>
          </apex:facet>     
          <apex:outputField value="{!tsk.ActivityDate}"/>
        </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:page>


      
logontokartiklogontokartik
Can you try putting this in one single line?

sApplySOQL = sApplySOQL + ' Order By ' + sortField + ' ' + sortDir +  ' limit ' + QueryLimit + ' offset ' + OffsetSize;

I tried the exact same code and it works fine for me. 

Thank you

Thakkar ParthThakkar Parth
I've this in one line only.Still the same error .When I Execute this in Console .Following is what i get .

14:08:27:145 FATAL_ERROR System.QueryException: unexpected token: <EOF>
And when I  Debug  it ,this is what i get 

14:08:27:144 USER_DEBUG [60]|DEBUG|Before Sorted Date is

Just to confirm, is it working when you click on ActivityDate column ? As soon as i click on the column name , it gives me error. Your help will be really appreciated . 


logontokartiklogontokartik
Ok. Sorry about that, 

I looked into the controller. Few issues 

1. When you click the toggle first time sApplySOQL is never populated, 
2. You need to populate sApplySOQL whenever query is built. 

Here is updated controller. Hope this helps. Please make sure your logic is right


public class PagingTasksController1{
    
    public List<Task> tasks {get;set;}
    public Task del;
    public Task taskDel;
    public Integer CountTotalRecords{get;set;}
    public String QueryString {get;set;}
    public Integer OffsetSize = 0;
    private Integer QueryLimit =3 ;
    public List<Task> lstTasks {get;set;}
    public String searchText {get;set;}
    public String rowIndex {get;set;}
    public Date mydate;
    public Integer totalCount {get;set;}
    public string sortField = 'Subject';  // default sort column
    private string sApplySOQL = '';
    public List<Task> delattendeeList {get;set;}
    
    public List<Task> delAttendees {get; set;}
    
    public PagingTasksController1(ApexPages.StandardController controller) {
        
        taskDel= (Task)controller.getRecord();
        tasks = [Select id,Subject,Status,ActivityDate,Owner.Name from Task];
        // this.Tasks=Tasks[0];
        totalCount = Tasks.size();
        
        delattendeeList = new List<Task>();
        delattendees = new List<Task>();
    }
    
    
    // the current sort direction. defaults to ascending
    public String sortDir {
        get  { if (sortDir == null) {  sortDir = 'asc'; } return sortDir;  }
        set;
    }
    
    // the current field to sort by. defaults to role name
    public String getsortField() {
        return sortField;
    }
    
    // the current field to sort by.
    public void setsortField(string value) {
        sortField = value;
    }
    
    // toggles the sorting of query from asc<-->desc
    public void toggleSort() {
        // simply toggle the direction
        sortDir = sortDir.equals('asc') ? 'desc' : 'asc';
        system.debug(sApplySOQL);
        integer iIndex = sApplySOQL.indexOf('Order By');
        if (iIndex > -1){
            sApplySOQL = sApplySOQL.substringBefore('Order By');
            sApplySOQL = sApplySOQL + ' Order By ' + sortField + ' ' + sortDir +  ' limit ' + QueryLimit + ' offset ' + OffsetSize;
        	System.debug('Before Sorted Date is ' +sApplySOQL);
         	tasks = Database.query(sApplySOQL );  // here it where gives me error
         
        }else{
            queryTasks();
        }
        
         
    }
       
    public PagingTasksController1 (){
        //CountTotalRecords= [select count() from Task];
        //String qStr2= '7/23/2014';
        
    }
    
    /* 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 qStr2= searchText;
        String strnormal = '';
        try{
            mydate = date.parse(qStr2);
        }catch(Exception e)
        { }
        
        String strDate = '';
        if(mydate != null) {
            // strnormal = String.valueOf(mydate );
            String[] qstr3 = String.valueOf(mydate).split(' ',2);
            strDate = ' ActivityDate =  '+ qstr3[0] + ' ';
        }else{
            
            strDate  =  '(Subject like \'%'+searchText +'%\' OR Status like \'%' +searchText+ '%\' OR Owner.Name like \'%' +searchText+ '%\') ' + ' Order By '  + sortField;
        }
        
        String qStr = 'Select Owner.Name,Subject,Status,ActivityDate from Task where '+strDate+' limit ' + QueryLimit + ' offset ' + OffsetSize;
        System.debug(qStr);
        sApplySOQL = qStr;
        tasks = Database.query(qStr);
        
    }
    
    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();
    }
    
    public void deleteRow(){
        delete new Task(Id = rowIndex);
        for (Integer i = 0; i < Tasks.size(); i++) {
            if (Tasks[i].Id == rowIndex) {
                Tasks.remove(i);
                break;
            }
        }
    }
}




Thakkar ParthThakkar Parth
You owe a Beer from me.. !!!! A BIG thanks to you..But a little foolish question to ask . If you "Preview " the Page , you will see Two title of Tasks ,whereas i've written only one title in pageblock ? 

I want to make it to one , Below is what appearing to me now :

Title displaying two times
logontokartiklogontokartik
Thats because you have two pageblockbuttons defined within pageblock. 

try this instead. Hope this helps . thx

<apex:page controller="PagingTasksController1" docType="html-5.0">
    <apex:form >
     <apex:variable var="rowNumber" value="{!0}"/>
        <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 headerValue="Action" >
              <apex:commandButton value="Delete" action="{!deleteRow}" reRender="pgTable"> 
                 <apex:param name="rowIndex" value="{!tsk.id}" assignTo="{!rowIndex}" />
              </apex:commandButton>              
           </apex:column> 
           
        <!-- <apex:column headerValue="Action" >
          <apex:outputLink value="{!URLFOR($Action.Task.Delete, .id,['retURL'='/apex/New_Test_task_Assignment'])}"> Delete</apex:outputLink>
        </apex:column>  -->
        <apex:column headerValue="Subject">
            <apex:facet name="header">
                <apex:commandLink value="Subject" action="{!toggleSort}" rerender="pgTable" >
                  <apex:param name="sortField" value="Subject" assignTo="{!sortField}"/>
                    <apex:outputPanel rendered="{!BEGINS(sortField,'Subject')}">
                        &nbsp;<apex:image value="{!IF(sortDir = 'desc','/img/arrowDown.gif','/img/arrowUp.gif')}"/>
                    </apex:outputPanel>
                </apex:commandLink>
            </apex:facet>     
          <apex:outputField value="{!tsk.Subject}"/>
        </apex:column>
           
        <apex:column headerValue="Status">
            <apex:facet name="header">
                <apex:commandLink value="Status" action="{!toggleSort}" rerender="pgTable" >
                      <apex:param name="sortField" value="Status" assignTo="{!sortField}"/>
                        <apex:outputPanel rendered="{!BEGINS(sortField,'Status')}">
                          &nbsp;<apex:image value="{!IF(sortDir = 'desc','/img/arrowDown.gif','/img/arrowUp.gif')}"/>
                        </apex:outputPanel>
                </apex:commandLink>
            </apex:facet>         
            <apex:outputField value="{!tsk.Status}"/>
        </apex:column>
       
        <apex:column headerValue="Assigned To">
            <apex:outputField value="{!tsk.Owner.Name}"/>
        </apex:column>
        
       <apex:column headerValue="Due Date">
          <apex:facet name="header">
                <apex:commandLink value="ActivityDate" action="{!toggleSort}" rerender="pgTable" >
                      <apex:param name="sortField" value="ActivityDate" assignTo="{!sortField}"/>
                        <apex:outputPanel rendered="{!BEGINS(sortField,'ActivityDate')}">
                          &nbsp;<apex:image value="{!IF(sortDir = 'desc','/img/arrowDown.gif','/img/arrowUp.gif')}"/>
                        </apex:outputPanel>
                </apex:commandLink>
          </apex:facet>     
          <apex:outputField value="{!tsk.ActivityDate}"/>
        </apex:column>   
            </apex:pageBlockTable> <br/>
		<div style="text-align:center;margin-left:auto;">
             <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..."/>
            </div>
      </apex:pageBlock>
    </apex:form>
  </apex:page>




Thakkar ParthThakkar Parth
Thanks logontokartik . This really helped me . You owe a beer !!!!