Many a times I came across scenarios where business demanded table content to be sorted on custom fields. Most generic scenarios I came across were in CIC. For example: Inbox items where we added a custom field "Customer Segment" to result list. This field holds information if client is 'Platinum, Gold or Silver'. Client demanded this list to be sorted on customer segment as more important client's mails should be attended first.
I wondered how to sort on a field which is not part of BOL structure. Then I found out that we can actually sort on value attributes too. This is something I would like to share with all who still assume that sorting on custom fields is not possible.
I will provide details for Inbox scenario, you may try it on any table view. Lets add a value attribute to context node ITEMS of view ICCMP_INBOX/InboxResultView. Name this as Z_CUSTOMER_SEG. Since this is a value attribute, you will have to decide on data to be displayed beforehand.
I prefer to calculate data for value attributes in ON_NEW_FOCUS (if already created) or DO_PREPARE_OUTPUT with a condition that IV_FIRST_TIME is set to 'X'. Save calculated data in buffer which can be used to display values of attributes. For this field, I calculated data to be displayed in DO_PREPARE_OUTPUT and saved it in buffer along with the value of field OBJECT_ID which is unique and part of BOL structure. This will be used to identify which value to display on each row. Now, retrieve value of OBJECT_ID from iterator in GET_Z_CUSTOMER_SEG and then read & display corresponding value for customer segment from buffer.
Next comes sorting part. We need to make field sortable before going for actual sorting code. Add following line of code to method GET_P_Z_CUSTOMER_SEG:
rv_value = 'TRUE'.
This will add sorting option to custom field on UI:
Next step: Redefine method EH_ON_SORT of context node class. In our case context node is ITEMS. Read column key from import parameter IV_HTMLB_EVENT_EX. If column key is Z_CUSTOMER_SEG then add following code:
In all other cases call superclass method. Till here we are done with calling custom sort method.
Now add interface IF_BOL_COL_SORTING to context node class. This will add method IF_BOL_COL_SORTING~IS_A_GREATER_B to class. This method is the place where actual sort logic will be written.
You can see import parameters IV_A & IV_B in this method. These are supplied by standard code for sort comparison and contain BOL entity reference.Read OBJECT_ID for IV_A and IV_B. Now read value of customer segment against these OBJECT_ID from buffer. If sort order provided is ascending then set RV_RESULT as 'X' if customer segment of IV_A is greater than IV_B else vice-versa.
This is all from customer end. SAP internally arranges collection as per RV_RESULT value.