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
Mathew Andresen 5Mathew Andresen 5 

Sort on different columns with custom sort

Hi,

I see how to implement custom sorting here
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_list_sorting_sobject.htm
And this is working for me.

If I want to sort on various custom columns is my only option to create a seperate class with a different sortable definition for each one?  Or is there a better way to do it.

For example, this is my current class where I sort on a total column that is part of a map of columns.
Thanks,
 
public class SortWrapper implements Comparable {

        public CompleteRowWrapper wrapper;
        
        // Constructor
        public SortWrapper(CompleteRowWrapper wrapper) {
            this.wrapper = wrapper;
        }
        
        // Compare opportunities based on the opportunity amount.
        public Integer compareTo(Object compareTo) {
            // Cast argument to SortWrapper
            SortWrapper compareToWrapper = (SortWrapper)compareTo;
            
            // The return value of 0 indicates that both elements are equal.
            Integer returnValue = 0;
            if (wrapper.partialRowList.amountMap.get('Total') < compareToWrapper.wrapper.partialRowList.amountMap.get('Total')) {
                // Set return value to a positive value.
                returnValue = 1;
            } else if (wrapper.partialRowList.amountMap.get('Total') > compareToWrapper.wrapper.partialRowList.amountMap.get('Total')) {
                // Set return value to a negative value.
                returnValue = -1;
            }
            
            return returnValue;       
        }
	} // end the sortable

 
Best Answer chosen by Mathew Andresen 5
pconpcon
Take a look over this [1] blog post.  It covers how to do it a little more dynamically.  If you know that all of your fields can be sorted by using an integer comparison then you can set the field name as part of a static variable and then use your sObject.get method with that static var as the parameter.

[1] http://blog.deadlypenguin.com/blog/2015/10/10/comparable-sorting-objects-in-salesforce/

All Answers

pconpcon
Take a look over this [1] blog post.  It covers how to do it a little more dynamically.  If you know that all of your fields can be sorted by using an integer comparison then you can set the field name as part of a static variable and then use your sObject.get method with that static var as the parameter.

[1] http://blog.deadlypenguin.com/blog/2015/10/10/comparable-sorting-objects-in-salesforce/
This was selected as the best answer
Mathew Andresen 5Mathew Andresen 5
very helpful, thanks