How to sort list of custom or standard object records

Sample Code:

Visualforce page:

<apex:page sidebar="false" Controller="Sample" showHeader="true" id="pg">
    <apex:pageBlock >
        <apex:pageBlockTable value="{!memList}" var="m">
            <apex:column value="{!m.Name}"/>
            <apex:column value="{!m.Age__c}"/>

Apex Controller:

public class Sample {   
    public List<Member__c> memList {get;set;}
    List<MemberWrapper> memberWrapperList = new List<MemberWrapper>();
    public sample() {
        memList = new List<Member__c>();
        memList = [SELECT Name, Age__c FROM Member__c];
        for(Member__c mem : memList){
            memberWrapperList.add(new MemberWrapper(mem));
        for(MemberWrapper MW : memberWrapperList){
    public class MemberWrapper implements Comparable {

        public Member__c member = new Member__c();
        // Constructor
        public MemberWrapper(Member__c memberRecord) {
            member = memberRecord;
        // Compare members based on the Member__c Age.
        public Integer compareTo(Object compareTo) {
            // Cast argument to MemberWrapper
            MemberWrapper compareTomember = (MemberWrapper)compareTo;
            // The return value of 0 indicates that both elements are equal.
            Integer returnValue = 0;
            if (member.Age__c > compareTomember.member.Age__c) {
                // Set return value to a positive value.
                returnValue = 1;
            } else if (member.Age__c < compareTomember.member.Age__c) {
                // Set return value to a negative value.
                returnValue = -1;
            return returnValue;       



1 comment:

  1. Its really helpful and working like charm.
    I want to approach the same sorting on click of the column header.
    Please give me an idea how to approach the same.


Sharing is Caring!!! Share this with your friends!!!

submit to reddit