如何将自定义 sortFunction 与 Grails gui:datatable 标记一起使用?

发布于 2024-11-19 03:00:52 字数 7403 浏览 4 评论 0原文

我在 Grails 中有一个数据表,其中有几个可排序的列。不幸的是,默认情况下排序区分大小写,因此“Zed”显示在“alice”之前。所以我想添加一个自定义的不区分大小写的排序功能。我将首先以这种方式对用户名列进行排序。

我已在 http://developer.yahoo.com/yui/datatable/< 阅读了有关 sortOptions 和 sortFunction 的信息/a> 但我似乎无法让它工作。

我将以下 JavaScript 添加到 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);
};

这是同一页面上的数据表定义:

<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> 

将“用户名”键更改为以下内容(无引号)没有帮助。

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

两种方法都会创建以下源。请注意,用户名的 sortOptions 为空。

            <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',
'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}, {'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>

当配置为标签时,有什么方法可以让数据表使用自定义 sortFunction 吗?

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',
'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}, {'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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浪漫之都 2024-11-26 03:00:52

listJSON 操作中,将 ignoreCase: true 参数添加到 list()。请参阅doc。这可能是唯一简单的方法。

如果您要支持分页,则无法将完全自定义的函数从 Javascript 级别推送到数据库级别 - 自定义函数将仅对当前页面进行排序,但分页将基于默认(按 id)排序。换句话说,自定义函数对于不超过 1 页的表格可以正常工作。

如果您在 listJSON 操作中使用 Criteria 或 SQL,您可以在一定程度上自定义排序 - 但您仍然仅限于 Hibernate 或 SQL等级。

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.

雨夜星沙 2024-11-26 03:00:52

在深入研究代码库后,我终于意识到排序是在服务器端完成的,因此我能够在那里解决问题。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文