开发者

How can I use a custom sortFunction with a Grails gui:datatable tag?

开发者 https://www.devze.com 2023-03-19 03:49 出处:网络
I have a datatable in Grails with several sortable columns.Unfortunately, the sort is case-sensitive by default, such that \"Zed\" is shown before \"alice\".So I want to add a custom case-insensitive

I have a datatable in Grails with several sortable columns. Unfortunately, the sort is case-sensitive by default, such that "Zed" is shown before "alice". So I want to add a custom case-insensitive sort function. I'll start by sorting the username column in this manner.

I have read about the sortOptions and sortFunction at http://developer.yahoo.com/yui/datatable/ but I can't seem to get it to work.

I added the following JavaScript to list.gsp:

var caseInsensitiveSortFunction = function(a, b, desc, field) {
    // See http://developer.yahoo.com/yui/datatable/ and look for 'sortFunction'
    // Set this function name as the sortFunction option
    // Deal with empty values
    if (!YAHOO.lang.isValue(a)) {
        return (!YAHOO.lang.isValue(b)) ? 0 : 1;
    } else if (!YAHOO.lang.isValue(b)) {
        return -1;
    }

    return YAHOO.util.Sort.compare(String(a).toLowerCase(), String(b).toLowerCase(), desc);
};

And here is the datatable definition on that same page:

<gui:dataTable id="userTable"
    controller="user" action="listJSON"
    rowsPerPage="20"
    sortedBy="username"
    columnDefs="[
                [key:'username', label:'Username', resizeable: false, sortable: true, sortOptions: { sortFunction: 'caseInsensitiveSortFunction' }],
                [key:'email', label:'Email', resizeable: false, sortable: true],
                [key:'firstName', label:'First Name', resizeable: false, sortable: true],
                [key:'lastName', label:'Last Name', resizeable: false, sortable: true],
                [key:'enabled', label:'Enabled', resizeable: false, sortable: true],
                [key:'accountLocked', label:'Locked', resizeable: false, sortable: true],
                [key:'roleDescription', label:'Role', resizeable: false, sortable: true]
            ]"
    draggableColumns="true"
    rowClickNavigation="true"
    paginatorConfig="[
            template:'{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {CurrentPageReport}',
            pageReportTemplate:'{totalRecords} total record(s)',
            alwaysVisible:true,
            containers:'dt-paginator'
            ]"/>
<div id="dt-paginator" class="yui-skin-sam yui-pg-container"></div> 

Changing the 'username' key to the following (sans quotes) does not help.

                [key:'username', label:'Username', resizeable: false, sortable: true, sortOptions: { sortFunction: caseInsensitiveSortFunction }],

Both approaches create the following source. Note that the sortOptions for the username is blank.

            <div id="dt_div_userTable"></div> 
            <script> 
            YAHOO.util.Event.onDOMReady(function () {
                var DataSource = YAHOO.util.DataSource,
                    DataTable  = YAHOO.widget.DataTable,
                    Paginator  = YAHOO.widget.Paginator;

                var userTable_ds = new DataSource('/admin/gpupUser/listJSON?');
                userTable_ds.responseType   = DataSource.TYPE_JSON;
                userTable_ds.connMethodPost=true;
                userTable_ds.responseSchema = {
                    resultsList : 'results',
                    fields      : ["username","email","firstName","lastName","enabled","accountLocked","roleDescription","dataUrl"],
                    metaFields  : {
                        totalRecords: 'totalRecords'
                    }
                };
                userTable_ds.doBeforeCallback = function(oRequest, oFullResponse, oParsedResponse, oCallback) {
                    return GRAILSUI.util.replaceDateStringsWithRealDates(oParsedResponse);
                };

                var userTable_paginator = new Paginator(
                    {'template': '{FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {CurrentPageReport}',
'pageReportTemplate': '{totalRecords} total record(s)',
'alwaysVisible': true,
'containers': 'dt-paginator',
'rowsPerPage': 20}
                );

                var registerEditorListener = function(editor, field, url,successCallback,failureCallback) {
                    editor.subscribe("saveEvent", function(oArgs) {
                        GRAILSUI.userTable.loadingDialog.show();
                        var editorCallback = {
                            success: successCallback,
                            failure: function(o) {
                                // revert the cell value
                                GRAILSUI.userTable.updateCell(oArgs.editor.getRecord(), field, oArgs.oldData);
                                // alert user
                                if (failureCallback)
                                  failureCallback(o);
                                else
                                  alert('Received an error during edit: ' + o.responseText);
                            }
                        };
                        YAHOO.util.Connect.asyncRequest('POST', url, editorCallback, 'id=' + oArgs.editor.getRecord().getData('id') + '&field=' + field + '&newValue=' + oArgs.newData);
                    });
                };



                var myColumnDefs = [{'key': 'username',
'label': 'Username',
'resizeable': false,
'sortable': true,
'sortOptions': }, {'key': 'email',
'label': 'Email',
'resize开发者_JAVA技巧able': false,
'sortable': true}, {'key': 'firstName',
'label': 'First Name',
'resizeable': false,
'sortable': true}, {'key': 'lastName',
'label': 'Last Name',
'resizeable': false,
'sortable': true}, {'key': 'enabled',
'label': 'Enabled',
'resizeable': false,
'sortable': true}, {'key': 'accountLocked',
'label': 'Locked',
'resizeable': false,
'sortable': true}, {'key': 'roleDescription',
'label': 'Role',
'resizeable': false,
'sortable': true}, {'key': 'dataUrl',
'type': 'dataDrillDown',
'hidden': true}];

                GRAILSUI.userTable = new GRAILSUI.DataTable('dt_div_userTable', myColumnDefs, userTable_ds, '', {
                    initialRequest         : 'max=20&offset=0&sort=username&order=asc&',
                    paginator              : userTable_paginator,
                    dynamicData            : true,
                    sortedBy               : {key: "username", dir: YAHOO.widget.DataTable.CLASS_ASC},
                    'draggableColumns': true,
'selectionMode': 'single',
'rowClickNavigate': false,
'rowClickMode': 'navigate',
'formatter': 'text'
                });
                // Update totalRecords on the fly with value from server
                GRAILSUI.userTable.handleDataReturnPayload = function(oRequest, oResponse, oPayload) {
                    oPayload.totalRecords = oResponse.meta.totalRecords;
                    return oPayload;
                };

                // Set up editing flow
                var highlightEditableCell = function(oArgs) {
                    var elCell = oArgs.target;
                    if(YAHOO.util.Dom.hasClass(elCell, "yui-dt-editable")) {
                        this.highlightCell(elCell);
                    }
                };
                GRAILSUI.userTable.subscribe("cellMouseoverEvent", highlightEditableCell);
                GRAILSUI.userTable.subscribe("cellMouseoutEvent", GRAILSUI.userTable.onEventUnhighlightCell);
                GRAILSUI.userTable.subscribe("cellClickEvent", GRAILSUI.userTable.onEventShowCellEditor);
            });
            </script> 

<div id="dt-paginator" class="yui-skin-sam yui-pg-container"></div>

Is there any way to get the datatable to use a custom sortFunction when configured as a tag?


In listJSON action, add ignoreCase: true parameter to list(). See doc. It's probably the only easy way.

You cannot push a totally custom function from Javascript level to database level, if you're going to support paging - custom function will sort current page only, but paging will be based on default (by id) ordering. In other words, custom function works correctly for no more then 1-page tables.

You can customize sorting to certain extent if you use a Criteria or SQL in listJSON action - but still, you're limited to Hibernate or SQL level.


After digging into the code base, I finally realized that the sorting was being done on the server side, so I was able to address the issue there.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号