2

I have recently had help creating a Wrapper class to combine 2 separate objects, Delivery_Note__c and Remittance_Advice__c, into one list, both with their own date fields. The list is then rendered on a Visualforce page, using <apex:repeat>.

The resulting list needs to be sorted by the date column (calculatedDate). I am trying to use compareTo, but with little success.

I have tried to follow this post which is similar, no luck.

Any thoughts?

UPDATE

As per Adrians suggestion, I have removed the bulk of the class to make the question a little easier to read.

APEX

public class CustomerStatementTableController {

    public class Wrapper implements Comparable {
        public Delivery_Note__c note {get; private set;}
        public Remittance_Advice__c remittance {get; private set;}
        public Date calculatedDate {get;private set;}

        public Wrapper(Delivery_Note__c n) {
            note = n;
            dataType = 'note';
            calculatedDate = note.Transaction_Date__c;
        }

        public Wrapper(Remittance_Advice__c r) {
            remittance = r;
            dataType = 'remittance';
            calculatedDate = remittance.Date__c;
        }

        public Integer compareTo(Object other) {
            Wrapper o = (Wrapper)other;

            if (note.Transaction_Date__c < remittance.Date__c) return -1;
        else if (note.Transaction_Date__c > remittance.Date__c) return 1;
        else return 0;
        }
    }

    public List<Wrapper> wrappers { get; private set; }
}
  • Your post would be improved if you take the trouble to remove lines which have nothing to do with the core issue. In this case, the only attributes which seem to matter are note and remittance, and the only method which matters is compareTo. – Adrian Larson Aug 2 '18 at 0:59
  • Your post is drastically improved, but still contains no detail about your actual requirements. Please edit this post to specify here what you are trying to achieve. The current implementation is difficult to interpret. – Adrian Larson Aug 2 '18 at 1:04
4

Based on your updates, simply compare calculatedDate between the passed in value (which you named other) and the instance calling the method. I find the following pattern readable and easy to understand:

public class Wrapper implements Comparable
{
    // other stuff

    public Integer compareTo(Object instance)
    {
        Wrapper that = (Wrapper)instance;
        if (this.calculatedDate > that.calculatedDate) return 1;
        if (this.calculatedDate < that.calculatedDate) return -1;
        return 0;
    }
}

The above implementation sorts by calculatedDate in ascending order. Simply reverse the signs to invert the order to descending.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.