0

I have in my controller:

  1. List NoteList
  2. List AttachmentList

My intention is to display it as a related list of notes and attachments as usually shown in salesforce. How do I combine them into a single list and display it on the page. I want this list to be sorted by LastModifiedDate. Please suggest how to proceed. Thanks

  • basic idea -- create wrapper, that would have Name, Id, LastModifiedDate,Note and Attachment references. Implement comparable interface for that wrapper. Create list of those wrappers, create instance for every note and attachment. Sort and display on VF as apex:repeat or apex:pageblocktable, doing some conditional rendering, like if attachement is given or if note is given – kurunve May 20 '16 at 11:19
2

A common approach is to create a small class that holds a reference to one or the other objects and provides properties (getters) that can be used by the page:

public class NoteOrAttachment implements Comparable {

    private Note n;
    private Attachment a;

    public NoteOrAttachment(Note n) {
        this.n = n;
    }

    public NoteOrAttachment(Attachment n) {
        this.a = a;
    }

    public DateTime getLastModifiedDate() {
        if (n != null) return n.LastModifiedDate;
        if (a != null) return a.LastModifiedDate;
        return null;
    }

    // Add other getters that take values from each object, sometimes from different fields

    public Integer compareTo(Object that) {
        Datetime d1 = this.getLastModifiedDate();
        Datetime d2 = ((NoteOrAttachment) that).getLastModifiedDate();
        if (d1 > d2) return -1;
        else if (d1 < d2) return 1;
        else return 0;
    }
}

Implementing Comparable allows the sort method of the list of these to be called in the controller to put them in order.

The page displays this combined list:

public NoteOrAttachment[] notesAndAttachments {
    get {
        if (notesAndAttachments == null) {
            notesAndAttachments = new NoteOrAttachment[] {};
            for (Note n : [select ... from Note ...]) {
                notesAndAttachments.add(new NoteOrAttachment(n));
            }
            for (Attachment a : [select ... from Attachment ...]) {
                notesAndAttachments.add(new NoteOrAttachment(a));
            }
            notesAndAttachments.sort();
        }
        return notesAndAttachments;
    }
    private set;
}

Don't query the Attachment Body as that can be large and so exceed the available heap or view state.

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.