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
Angela SchloederAngela Schloeder 

Sort by column header on vf page.

I'll start by saying, I am not a developer by any means. I'm still plugging along trying to finish a vf page started by a freelance developer that left me hanging. I have done a lot of research, but cannot seem to figure out how to be able to click on the column headers and have it (sortDirection='ASC','▼','▲').

Any help is enormously appreciated. I'm going crazy with this thing.

My Controller:
public with sharing class MeetingBacklogController
{

    public String getSortDirection() {
        return null;
    }


    public String sortExpression { get; set; }

    public PageReference ViewData() {
        return null;
    }


    public String events { get; set; }
    public List<Event> eventsList{get; set;}
    public Map<Id, sObject> relatedRecords{get; set;}
    
    private Map<Id, Event> originalEventsMap;
    
    public MeetingBacklogController()
    {
        init(true);
    }
    
    private void init(Boolean updateUI)
    {
        Set<String> meetingProgressionValues=new Set<String>();
        for(PicklistEntry entry: Event.Meeting_Progression__c.getDescribe().getPicklistValues())
        {
            if(entry.getValue().startsWithIgnoreCase('M') || entry.getValue().startsWithIgnoreCase('Conf'))
            {
                meetingProgressionValues.add(entry.getValue());
            }
        }
        originalEventsMap=new Map<Id, Event>([
            SELECT Id, Set_By__c, Attendee__c, Meeting_Progression__c, Exec_Invites__c,
            Client_Invites__c, Meeting_Status__c,
            ActivityDate, StartDateTime, Subject, AccountId, Account.Name, WhoId, Who.Name, Who.Title,
            Location, Meeting_Location__c, IsChild
            FROM Event
            WHERE StartDateTime=NEXT_N_DAYS:90
            AND Meeting_Progression__c IN :meetingProgressionValues
            AND Meeting_Status__c NOT IN ('CCLP','CP','CC','MP','MC','AM')
            AND IsChild=false
        ]);
               
        relatedRecords=new Map<Id, SObject>();
        for(Event record: originalEventsMap.values())
        {
            relatedRecords.put(record.WhoId, Null);
        }
        relatedRecords.putAll([SELECT Title FROM Lead WHERE Id IN :relatedRecords.keySet()]);
        relatedRecords.putAll([SELECT Title FROM Contact WHERE Id IN :relatedRecords.keySet()]);
        relatedRecords.put(Null, new Contact());
        
        eventsList=new List<Event>();
        if(updateUI)
        {
            eventsList=originalEventsMap.values().deepClone(true, true, true);
            eventsList.sort();
        }
    }
    
    public void refresh()
    {
        init(true);
    }
    
    public void save()
    {
        List<Event> eventsToBeUpdateList=new List<Event>();
        
        for(Integer i=0; i<originalEventsMap.values().size(); i++)
        {
            for(Integer j=0; j<eventsList.size(); j++)
            {
                if(originalEventsMap.values()[i].Id==eventsList[j].Id && originalEventsMap.values()[i]!=eventsList[j])
                {
                    eventsToBeUpdateList.add(eventsList[j]);
                    system.debug('eventsList[j]---->'+eventsList[j]);
                    break;
                }
            }
        }
        Boolean updateUI=true;
        
        try
        {
            Integer numberOfRecordsUpdated=0;
            for(Database.SaveResult result: Database.update(eventsToBeUpdateList, false))
            {
                updateUI&=result.isSuccess();
                if(result.isSuccess())
                {
                    numberOfRecordsUpdated=numberOfRecordsUpdated+1;
                }
            }
            
            init(updateUI);
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, numberOfRecordsUpdated+' record'+(numberOfRecordsUpdated==1?'':'s')+' saved.'));
        }
        catch(Exception e)
        {
            ApexPages.addMessages(e);
        }
    }
}

VF Page:

<apex:page controller="MeetingBacklogController" tabStyle="Event">
    <apex:sectionHeader title="Event" subtitle="Meeting Backlog" />
    <apex:form id="form">
         <apex:pageBlock >
            <apex:pageBlockButtons >
                <apex:commandButton action="{!save}" id="saveButton" value="Save"  reRender="form" status="status" />
                <apex:commandButton value="Refresh" action="{!refresh}" reRender="form" status="status" />
                <apex:commandButton onclick="resetInlineEdit()" id="cancelButton" value="Cancel"/>
                <apex:actionStatus startText="Updating..." id="status" />
            </apex:pageBlockButtons>
                   <apex:pageMessages />
            <apex:pageMessage severity="info" rendered="{!eventsList.size=0}">
                No records found
                    </apex:pageMessage>
            <apex:pageBlockTable rendered="{!eventsList.size>0}" value="{!eventsList}" var="event">
                <apex:column headerValue="{!$ObjectType.Event.fields.Set_By__c.Label}" value="{!event.Set_By__c}" />
                <apex:column headerValue="{!$ObjectType.Event.fields.Attendee__c.Label}" >
                <apex:outputField value="{!event.Attendee__c}" >
                        </apex:outputField>
                </apex:column>
                <apex:column headerValue="{!$ObjectType.Event.fields.Meeting_Progression__c.Label}">
                <apex:outputField value="{!event.Meeting_Progression__c}" >
                        </apex:outputField>
               </apex:column>
                <apex:column headerValue="{!$ObjectType.Event.fields.Client_Invites__c.Label}">
                    <apex:outputField value="{!event.Client_Invites__c}" >
                        </apex:outputField>
               </apex:column>
                <apex:column headerValue="{!$ObjectType.Event.fields.Exec_Invites__c.Label}">
                    <apex:outputField value="{!event.Exec_Invites__c}" >
                        </apex:outputField>
                </apex:column>
                <apex:column headerValue="{!$ObjectType.Event.fields.Meeting_Status__c.Label}">
                    <apex:outputField value="{!event.Meeting_Status__c}" >
                        </apex:outputField>
                </apex:column>
                <apex:facet name="header">   
           <apex:commandLink action="{!ViewData}" value="StartDateTime{!IF(sortExpression=='name',IF(sortDirection='ASC','▼','▲'),'')}" id="cmdSort">
             <apex:param value="name" name="column" assignTo="{!sortExpression}" ></apex:param>
           </apex:commandLink>
         </apex:facet>
                <apex:column headerValue="{!$ObjectType.Event.fields.StartDateTime.Label}">
                        <apex:outputField value=" {!event.StartDateTime}" >
                    </apex:outputField>
                </apex:column>
                     <apex:column headervalue="{!$ObjectType.Event.fields.Subject.Label}">
                        <apex:outputField value="{!event.Subject}" label="Subject" >
                        </apex:outputField>
            </apex:column>
                    <apex:column headerValue="{!$ObjectType.Event.fields.Location.Label}" >
                    <apex:outputField value="{!event.Location}" >
                    </apex:outputField>
                </apex:column>
                <apex:column headerValue="{!$ObjectType.Event.fields.Subject.Label}" value="{!event.Subject}" />
                 <apex:column headerValue="{!$ObjectType.Account.fields.Name.Label}" value="{!event.AccountId}" />
                 <apex:column headerValue="{!$ObjectType.Contact.fields.Name.Label}" value="{!event.WhoId}" />
                <apex:column headerValue="{!$ObjectType.Contact.fields.Title.Label}" value="{!relatedRecords[event.WhoId]['Title']}" />
                  <apex:column headerValue="{!$ObjectType.Event.fields.Meeting_Location__c.Label}" >
                <apex:outputField value=" {!event.Meeting_Location__c}" >
                </apex:outputField>
                         </apex:column>
                <apex:inlineEditSupport event="ondblClick"
                            showOnEdit="saveButton,cancelButton" hideOnEdit="editButton" />
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>


Regards,
Very frustrated Admin
Amit Chaudhary 8Amit Chaudhary 8
Please check below post. Full code on below blog.  I hope that will help you
http://salesforcesource.blogspot.in/2008/11/adding-sorting-capability-to.html

Can you please let us know your requirement in detail so that we can help you here.

Thanks
Amit Chaudhary
amit.salesforce21@gmail.com
Rahul KhedekarRahul Khedekar
/*
  The following code will show a VF page with two columns in a table :- Account ID and Account Name. Clicking on "Account Name" header in the table will cause sorting of the data in that column. If it is sorted in ascending order, then it will switch to descending order and vice-versa.
*/
public class AccountSortHeader
{
    public List<Account> allAcc {get;set;}
    public String sortDirection {get;set;}
    
    public AccountSortHeader()
    {
        sortDirection = 'asc';
        String query = 'Select Id, name from Account order by Name ' + sortDirection;
        allAcc = Database.query(query);
    }
    
    public pageReference sortAccNamecolumn()
    {
        if(sortDirection == 'asc')
        {
            sortDirection = 'desc';
        }
        else if(sortDirection == 'desc')
        {
            sortDirection = 'asc';
        }
        String query = 'Select Id, name from Account order by Name ' + sortDirection;
        allAcc = Database.query(query);
        return null;
    }
}

VF page :-
<apex:page controller="AccountSortHeader">
  <apex:form>
    <apex:pageBlock>
      <apex:pageBlockTable value="{!allAcc}" var="a" id="AccountData">
        <apex:column headerValue="Account ID" value="{!a.Id}"/>
        <apex:column value="{!a.Name}">
          <apex:facet name="header">
          <!-- Any facet whose name is header will apply to the header of this column in the pageBlockTable -->
            <apex:outputPanel>
              <apex:commandLink value="Account Name" action="{!sortAccNamecolumn}" reRender="AccountData"/>
            </apex:outputPanel>
          </apex:facet>
        </apex:column>
      </apex:pageBlockTable>
    </apex:pageBlock>
  </apex:form>
</apex:page>

Go to this VF page using this :-
https://c.ap5.visual.force.com/apex/vfAccountSortHeader