opnsense_bootgrid_plugin.js 10.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
/**
 *    Copyright (C) 2015 Deciso B.V.
 *
 *    All rights reserved.
 *
 *    Redistribution and use in source and binary forms, with or without
 *    modification, are permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *
 *    2. Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *
 *    THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 *    AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *    AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
 *    OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 *    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 *    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 *    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *    POSSIBILITY OF SUCH DAMAGE.
 *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 */

/**
 * wrapper around bootgrid component to use our defaults (including scaling footer)
 * @param id
 * @param sourceUrl
34
 * @param options associative array containing extra bootgrid options or overwrites
35
 */
36 37 38
function stdBootgridUI(obj, sourceUrl, options) {
    // set defaults our defaults
    var gridopt = {
39 40 41 42 43 44
        ajax: true,
        selection: true,
        multiSelect: true,
        rowCount:[7,14,20,-1],
        url: sourceUrl,
        formatters: {
45
            "commands": function (column, row) {
46 47
                return "<button type=\"button\" class=\"btn btn-xs btn-default command-edit\" data-row-id=\"" + row.uuid + "\"><span class=\"fa fa-pencil\"></span></button> " +
                    "<button type=\"button\" class=\"btn btn-xs btn-default command-delete\" data-row-id=\"" + row.uuid + "\"><span class=\"fa fa-trash-o\"></span></button>";
48 49 50
            },
            "rowtoggle": function (column, row) {
                if (parseInt(row[column.id], 2) == 1) {
51
                    return "<span style=\"cursor: pointer;\" class=\"fa fa-check-square-o command-toggle\" data-value=\"1\" data-row-id=\"" + row.uuid + "\"></span>";
52
                } else {
53
                    return "<span style=\"cursor: pointer;\" class=\"fa fa-square-o command-toggle\" data-value=\"0\" data-row-id=\"" + row.uuid + "\"></span>";
54
                }
55 56
            }
        }
57 58 59 60 61 62 63 64 65 66 67
    };

    // merge additional options (if any)
    if (options != undefined) {
        $.each(options,  function(key, value) {
            gridopt[key] = value;
        });
    }

    // construct a new grid
    var grid = obj.bootgrid(gridopt).on("loaded.rs.jquery.bootgrid", function (e)
68 69 70
    {
        // scale footer on resize
        $(this).find("tfoot td:first-child").attr('colspan',$(this).find("th").length - 1);
71 72 73 74 75 76
        $(this).find('tr[data-row-id]').each(function(){
            if ($(this).find('[class*="command-toggle"]').first().data("value") == "0") {
                $(this).addClass("text-muted");
            }
        });

77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
    })

    return grid;
}

/**
 * creates new bootgrid object and links actions to our standard templates
 * uses the following data properties to define functionality:
 *      data-editDialog : id of the edit dialog to use (  see base_dialog.volt template for details )
 *      data-action [add] : set data-action "add" to create a new record
 *      data-action [deleteSelected]: set data-action "deleteSelected" to delete selected items
 *
 * and uses the following properties (params array):
 *  search  : url to search action (GET)
 *  get     : url to get data action (GET) will be suffixed by uuid
 *  set     : url to set data action (POST) will be suffixed by uuid
 *  add     : url to create a new data record (POST)
 *  del     : url to del item action (POST) will be suffixed by uuid
 *
 * @param params
 * @returns {*}
 * @constructor
 */
$.fn.UIBootgrid = function (params) {
    return this.each((function(){
        var gridId = $(this).attr('id');
        var gridParams = params;
        if (gridParams != undefined) {
            if (gridParams['search'] != undefined) {
                // create new bootgrid component and link source
107
                var grid = stdBootgridUI($(this), gridParams['search'],gridParams['options']);
108 109 110 111 112 113 114 115 116

                // edit dialog id to use ( see base_dialog.volt template for details)
                var editDlg = $(this).attr('data-editDialog');

                // link edit and delete event buttons
                grid.on("loaded.rs.jquery.bootgrid", function(){
                    // edit item
                    grid.find(".command-edit").on("click", function(e)
                    {
117
                        if (editDlg != undefined && gridParams['get'] != undefined) {
118 119 120 121 122
                            var uuid = $(this).data("row-id");
                            var urlMap = {};
                            urlMap['frm_' + editDlg] = gridParams['get'] + uuid;
                            mapDataToFormUI(urlMap).done(function () {
                                // update selectors
123
                                formatTokenizersUI();
124 125 126 127 128 129 130 131 132
                                $('.selectpicker').selectpicker('refresh');
                                // clear validation errors (if any)
                                clearFormValidation('frm_' + editDlg);
                            });

                            // show dialog for pipe edit
                            $('#'+editDlg).modal({backdrop: 'static', keyboard: false});
                            // define save action
                            $("#btn_"+editDlg+"_save").unbind('click').click(function(){
133 134 135 136 137 138 139 140 141
                                if (gridParams['set'] != undefined) {
                                    saveFormToEndpoint(url=gridParams['set']+uuid,
                                        formid='frm_' + editDlg, callback_ok=function(){
                                            $("#"+editDlg).modal('hide');
                                            $("#"+gridId).bootgrid("reload");
                                        }, true);
                                } else {
                                    console.log("[grid] action set missing")
                                }
142 143
                            });
                        } else {
144
                            console.log("[grid] action get or data-editDialog missing")
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
                        }
                    }).end();

                    // delete item
                    grid.find(".command-delete").on("click", function(e)
                    {
                        if (gridParams['del'] != undefined) {
                            var uuid=$(this).data("row-id");
                            stdDialogRemoveItem('Remove selected item?',function() {
                                ajaxCall(url=gridParams['del'] + uuid,
                                    sendData={},callback=function(data,status){
                                        // reload grid after delete
                                        $("#"+gridId).bootgrid("reload");
                                    });
                            });
                        } else {
161
                            console.log("[grid] action del missing")
162 163
                        }
                    }).end();
164 165 166 167 168 169 170 171 172 173 174 175

                    // toggle item
                    grid.find(".command-toggle").on("click", function(e)
                    {
                        if (gridParams['toggle'] != undefined) {
                            var uuid=$(this).data("row-id");
                            ajaxCall(url=gridParams['toggle'] + uuid,
                                sendData={},callback=function(data,status){
                                    // reload grid after delete
                                    $("#"+gridId).bootgrid("reload");
                                });
                        } else {
176
                            console.log("[grid] action toggle missing")
177 178
                        }
                    }).end();
179 180 181
                });

                // link Add new to child button with data-action = add
182 183
                $(this).find("*[data-action=add]").click(function(){
                    if ( gridParams['get'] != undefined && gridParams['add'] != undefined) {
184 185 186 187
                        var urlMap = {};
                        urlMap['frm_' + editDlg] = gridParams['get'];
                        mapDataToFormUI(urlMap).done(function(){
                            // update selectors
188
                            formatTokenizersUI();
189 190 191 192 193
                            $('.selectpicker').selectpicker('refresh');
                            // clear validation errors (if any)
                            clearFormValidation('frm_' + editDlg);
                        });

194
                        // show dialog for edit
195 196 197 198 199 200 201 202 203
                        $('#'+editDlg).modal({backdrop: 'static', keyboard: false});
                        //
                        $("#btn_"+editDlg+"_save").unbind('click').click(function(){
                            saveFormToEndpoint(url=gridParams['add'],
                                formid='frm_' + editDlg, callback_ok=function(){
                                    $("#"+editDlg).modal('hide');
                                    $("#"+gridId).bootgrid("reload");
                                }, true);
                        });
204 205 206 207
                    }  else {
                        console.log("[grid] action add missing")
                    }
                });
208 209

                // link delete selected items action
210 211
                $(this).find("*[data-action=deleteSelected]").click(function(){
                    if ( gridParams['del'] != undefined) {
212 213 214 215 216 217 218 219 220 221 222 223 224
                        stdDialogRemoveItem("Remove selected items?",function(){
                            var rows =$("#"+gridId).bootgrid('getSelectedRows');
                            if (rows != undefined){
                                var deferreds = [];
                                $.each(rows, function(key,uuid){
                                    deferreds.push(ajaxCall(url=gridParams['del'] + uuid, sendData={},null));
                                });
                                // refresh after load
                                $.when.apply(null, deferreds).done(function(){
                                    $("#"+gridId).bootgrid("reload");
                                });
                            }
                        });
225 226 227 228
                    } else {
                        console.log("[grid] action del missing")
                    }
                });
229 230 231 232 233 234

                return grid;
            }
        }
    }));
};