I have implemented a Wrapper class using this: Salesforce Wrapper Class. Now I am trying to implement sorting for the column header which turns out to be throwing error:
Invalid field Account.Name for Contact. Error is in expression '{!sortWrpLst}' in page myVfWrapperPage: Class.myWrapper.cContact.compareTo: line **, Column 1 Class: Class.myWrapper.cContact. sortWrpLst: line **, Column 1
An unexpected error has occurred. Your development organization has been notified.
Visualforce Page:
<apex:page standardController="Case" extensions="myWrapper" tabStyle="Create_New_Incident__tab">
<apex:form >
<apex:pageMessages />
<apex:pageBlockTable value="{!contacts}" var="c" id="table">
<apex:column >
<apex:facet name="header">
<apex:inputCheckbox onclick="selectCheckboxes(this,'inputId')"/>
</apex:facet>
<apex:inputCheckbox value="{!c.selected}" id="inputId"/>
</apex:column>
<apex:column>
<apex:facet name="header">
<apex:commandLink value="Name {!IF(compareField=='Name',IF(sortOrder='asc','▼','▲'),'')}" action="{!sortWrpLst}">
<apex:param name="compareField" value="Name" assignTo="{!compareField}" />
<apex:param name="orderType" value="{!IF(sortOrder='asc', 'desc', 'asc')}" assignTo="{!sortOrder}" />
</apex:commandLink>
</apex:facet>
<apex:outputField value="{!c.con.Name}"/>
</apex:column>
<apex:column>
<apex:facet name="header">
<apex:commandLink value="Hospital {!IF(compareField=='Account.Name',IF(sortOrder='asc','▼','▲'),'')}" action="{!sortWrpLst}">
<apex:param name="compareField" value="Account.Name" assignTo="{!compareField}" />
<apex:param name="orderType" value="{!IF(sortOrder='asc', 'desc', 'asc')}" assignTo="{!sortOrder}" />
</apex:commandLink>
</apex:facet>
<apex:outputField value="{!c.con.Account.Name}"/>
</apex:column>
</apex:pageBlockTable>
</apex:form>
Class:
public class myWrapper{
public List<cContact> contactList {get; set;}
public static String compareField {get; set;}
public static String sortOrder{get; set;}
public myWrapper(){
getContacts();
}
public List<cContact> getContacts() {
List<Contact> conList = [SELECT Id, Name, Email, Phone, Account.Name FROM Contact WHERE Checkbox__c = TRUE ];
contactList = new List<cContact>();
for(Contact c: conList) {
contactList.add(new cContact(c, false));
}
return contactList;
}
public void sortWrpLst() {
contactList.sort();
}
public class cContact implements Comparable {
public Contact con {get; set;}
public Boolean selected {get; set;}
public cContact(Contact c, boolean selectedBox) {
con = c;
selected = selectedBox;
}
public Integer compareTo(Object vCase)
{
cContact caseToComp = (cContact)vCase;
if((String)con.get(compareField) > (String)caseToComp.con.get(compareField)){
return sortOrder.equals('asc') ? 1 : 0;
}
else {
return sortOrder.equals('asc') ? 0 : 1;
}
}
}
}
Referred: Dynamic Sorting