Advertisement
Guest User

Untitled

a guest
Nov 18th, 2018
438
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * @summary altEditor
  3.  * @description Lightweight editor for DataTables
  4.  * @version 2.0
  5.  * @file dataTables.editor.free.js
  6.  * @author kingkode (www.kingkode.com)
  7.  *  Modified by: Kasper Olesen (https://github.com/KasperOlesen), Luca Vercelli (https://github.com/luca-vercelli), Zack Hable (www.cobaltdevteam.com)
  8.  * @contact www.kingkode.com/contact
  9.  * @contact zack@cobaltdevteam.com
  10.  * @copyright Copyright 2016 Kingkode
  11.  *
  12.  * This source file is free software, available under the following license: MIT
  13.  * license
  14.  *
  15.  * This source file is distributed in the hope that it will be useful, but
  16.  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  17.  * FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
  18.  *
  19.  *
  20.  */
  21. (function (factory) {
  22.     if (typeof define === 'function' && define.amd) {
  23.         // AMD
  24.         define(['jquery', 'datatables.net'], function ($) {
  25.             return factory($, window, document);
  26.         });
  27.     }
  28.     else if (typeof exports === 'object') {
  29.         // CommonJS
  30.         module.exports = function (root, $) {
  31.             if (!root) {
  32.                 root = window;
  33.             }
  34.  
  35.             if (!$ || !$.fn.dataTable) {
  36.                 $ = require('datatables.net')(root, $).$;
  37.             }
  38.  
  39.             return factory($, root, root.document);
  40.         };
  41.     }
  42.     else {
  43.         // Browser
  44.         factory(jQuery, window, document);
  45.     }
  46. })
  47. (function ($, window, document, undefined) {
  48.     'use strict';
  49.     var DataTable = $.fn.dataTable;
  50.  
  51.     var _instance = 0;
  52.  
  53.     /**
  54.      * altEditor provides modal editing of records for Datatables
  55.      *
  56.      * @class altEditor
  57.      * @constructor
  58.      * @param {object}
  59.      *            oTD DataTables settings object
  60.      * @param {object}
  61.      *            oConfig Configuration object for altEditor
  62.      */
  63.     var altEditor = function (dt, opts) {
  64.         if (!DataTable.versionCheck || !DataTable.versionCheck('1.10.8')) {
  65.             throw ("Warning: altEditor requires DataTables 1.10.8 or greater");
  66.         }
  67.  
  68.         // User and defaults configuration object
  69.         this.c = $.extend(true, {}, DataTable.defaults.altEditor,
  70.             altEditor.defaults, opts);
  71.  
  72.         /**
  73.          * @namespace Settings object which contains customisable information
  74.          *            for altEditor instance
  75.          */
  76.         this.s = {
  77.             /** @type {DataTable.Api} DataTables' API instance */
  78.             dt: new DataTable.Api(dt),
  79.  
  80.             /** @type {String} Unique namespace for events attached to the document */
  81.             namespace: '.altEditor' + (_instance++)
  82.         };
  83.  
  84.         /**
  85.          * @namespace Common and useful DOM elements for the class instance
  86.          */
  87.         this.dom = {
  88.             /** @type {jQuery} altEditor handle */
  89.             modal: $('<div class="dt-altEditor-handle"/>'),
  90.         };
  91.  
  92.         /* Constructor logic */
  93.         this._constructor();
  94.     }
  95.  
  96.     $.extend(
  97.         altEditor.prototype,
  98.         {
  99.             /***************************************************************
  100.              * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  101.              * Constructor * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  102.              */
  103.  
  104.             /**
  105.              * Initialise the RowReorder instance
  106.              *
  107.              * @private
  108.              */
  109.             _constructor: function () {
  110.                 var that = this;
  111.                 var dt = this.s.dt;
  112.  
  113.                 if (dt.settings()[0].oInit.onAddRow)
  114.                     that.onAddRow = dt.settings()[0].oInit.onAddRow;
  115.                 if (dt.settings()[0].oInit.onDeleteRow)
  116.                     that.onDeleteRow = dt.settings()[0].oInit.onDeleteRow;
  117.                 if (dt.settings()[0].oInit.onEditRow)
  118.                     that.onEditRow = dt.settings()[0].oInit.onEditRow;
  119.  
  120.                 this._setup();
  121.  
  122.                 dt.on('destroy.altEditor', function () {
  123.                     dt.off('.altEditor');
  124.                     $(dt.table().body()).off(that.s.namespace);
  125.                     $(document.body).off(that.s.namespace);
  126.                 });
  127.             },
  128.  
  129.             /***************************************************************
  130.              * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  131.              * Private methods * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  132.              */
  133.  
  134.             /**
  135.              * Setup dom and bind button actions
  136.              *
  137.              * @private
  138.              */
  139.             _setup: function () {
  140.                 var that = this;
  141.                 var dt = this.s.dt;
  142.  
  143.                 var modal = '<div class="modal fade" id="altEditor-modal" tabindex="-1" role="dialog">' +
  144.                     '<div class="modal-dialog">' +
  145.                     '<div class="modal-content">' +
  146.                     '<div class="modal-header">' +
  147.                     '<h4 style="padding-top: 1rem;padding-left: 1rem;" class="modal-title"></h4>' +
  148.                     '<button style="margin: initial;" type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>' +
  149.                     '</div>' +
  150.                     '<div class="modal-body">' +
  151.                     '<p></p>' +
  152.                     '</div>' +
  153.                     '<div class="modal-footer">' +
  154.                     '<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>' +
  155.                     '<input type="submit" form="altEditor-form" class="btn btn-primary"></input>' +
  156.                     '</div>' +
  157.                     '</div>' +
  158.                     '</div>' +
  159.                     '</div>';
  160.                 // add modal
  161.                 $('body').append(modal);
  162.  
  163.                 // add Edit Button
  164.                 if (dt.button('edit:name')) {
  165.                     dt.button('edit:name').action(function (e, dt, node, config) {
  166.                         that._openEditModal();
  167.                     });
  168.  
  169.                     $(document).on('click', '#editRowBtn', function (e) {
  170.                         if (that._inputValidation()) {
  171.                             e.preventDefault();
  172.                             e.stopPropagation();
  173.                             that._editRowData();
  174.                         }
  175.                     });
  176.                 }
  177.  
  178.                 // add Delete Button
  179.                 if (dt.button('delete:name')) {
  180.                     dt.button('delete:name').action(function (e, dt, node, config) {
  181.                         that._openDeleteModal();
  182.                     });
  183.  
  184.                     $(document).on('click', '#deleteRowBtn', function (e) {
  185.                         e.preventDefault();
  186.                         e.stopPropagation();
  187.                         that._deleteRow();
  188.                         $(this).prop('disabled', true);
  189.                     });
  190.                 }
  191.  
  192.                 // add Add Button
  193.                 if (dt.button('add:name')) {
  194.                     dt.button('add:name').action(function (e, dt, node, config) {
  195.                         that._openAddModal();
  196.                     });
  197.  
  198.                     $(document).on('click', '#addRowBtn', function (e) {
  199.                         if (that._inputValidation()) {
  200.                             e.preventDefault();
  201.                             e.stopPropagation();
  202.                             that._addRowData();
  203.                         }
  204.                     });
  205.                 }
  206.  
  207.                 // add Refresh button
  208.                 if (this.s.dt.button('refresh:name')) {
  209.                     this.s.dt.button('refresh:name').action(function (e, dt, node, config) {
  210.                         if (dt.ajax && dt.ajax.url()) {
  211.                             dt.ajax.reload();
  212.                         }
  213.                     });
  214.                 }
  215.             },
  216.  
  217.             /**
  218.              * Emit an event on the DataTable for listeners
  219.              *
  220.              * @param {string}
  221.              *            name Event name
  222.              * @param {array}
  223.              *            args Event arguments
  224.              * @private
  225.              */
  226.             _emitEvent: function (name, args) {
  227.                 this.s.dt.iterator('table', function (ctx, i) {
  228.                     $(ctx.nTable).triggerHandler(name + '.dt', args);
  229.                 });
  230.             },
  231.  
  232.             /**
  233.              * Open Edit Modal for selected row
  234.              *
  235.              * @private
  236.              */
  237.             _openEditModal: function () {
  238.                 var that = this;
  239.                 var dt = this.s.dt;
  240.                 var columnDefs = [];
  241.  
  242.                 // Adding column attributes to object.
  243.                 // Please set the ID as readonly.
  244.                 for (var i in dt.context[0].aoColumns) {
  245.                     var obj = dt.context[0].aoColumns[i];
  246.                     columnDefs[i] = {
  247.                         title: obj.sTitle,
  248.                         name: obj.data ? obj.data : obj.mData,
  249.                         type: (obj.type ? obj.type : 'text'),
  250.                         options: (obj.options ? obj.options : []),
  251.                         msg: (obj.errorMsg ? obj.errorMsg : ''),
  252.                         hoverMsg: (obj.hoverMsg ? obj.hoverMsg : ''),
  253.                         pattern: (obj.pattern ? obj.pattern : '.*'),
  254.                         special: (obj.special ? obj.special : ''),
  255.                         unique: (obj.unique ? obj.unique : false),
  256.                         uniqueMsg: (obj.uniqueMsg ? obj.uniqueMsg : ''),
  257.                         maxLength: (obj.maxLength ? obj.maxLength : false),
  258.                         multiple: (obj.multiple ? obj.multiple : false),
  259.                         select2: (obj.select2 ? obj.select2 : false)
  260.                     };
  261.                 }
  262.                 var adata = dt.rows({
  263.                     selected: true
  264.                 });
  265.  
  266.                 // Building edit-form
  267.                 var data = "";
  268.  
  269.                 data += "<form name='altEditor-form' role='form'>";
  270.  
  271.                 for (var j in columnDefs) {
  272.                     // handle hidden fields
  273.                     if (columnDefs[j].type.indexOf("hidden") >= 0) {
  274.                         data += "<input type='hidden' id='" + columnDefs[j].name + "' value='" + adata.data()[0][columnDefs[j].name] + "'></input>";
  275.                     }
  276.                     else {
  277.                         // handle fields that are visible to the user
  278.                         data += "<div style='margin-left: initial;margin-right: initial;' class='form-group row'>"
  279.                         data += "<div class='col-sm-3 col-md-3 col-lg-3 text-right' style='padding-top:4px;'>"
  280.                         data += "<label for='" + columnDefs[j].title + "'>" + columnDefs[j].title + ":</label></div>"
  281.                         data += "<div class='col-sm-8 col-md-8 col-lg-8'>";
  282.  
  283.                         // Adding text-inputs and errorlabels
  284.                         if (columnDefs[j].type.indexOf("text") >= 0) {
  285.                             data += "<input type='"
  286.                                 + that._quoteattr(columnDefs[j].type)
  287.                                 + "' id='"
  288.                                 + that._quoteattr(columnDefs[j].name)
  289.                                 + "'  pattern='"
  290.                                 + that._quoteattr(columnDefs[j].pattern)
  291.                                 + "'  title='"
  292.                                 + that._quoteattr(columnDefs[j].hoverMsg)
  293.                                 + "' name='"
  294.                                 + that._quoteattr(columnDefs[j].title)
  295.                                 + "' placeholder='"
  296.                                 + that._quoteattr(columnDefs[j].title)
  297.                                 + "' data-special='"
  298.                                 + that._quoteattr(columnDefs[j].special)
  299.                                 + "' data-errorMsg='"
  300.                                 + that._quoteattr(columnDefs[j].msg)
  301.                                 + "' data-uniqueMsg='"
  302.                                 + that._quoteattr(columnDefs[j].uniqueMsg)
  303.                                 + "' data-unique='"
  304.                                 + columnDefs[j].unique
  305.                                 + "'"
  306.                                 + (columnDefs[j].maxLength == false ? "" : " maxlength='" + columnDefs[j].maxLength + "'")
  307.                                 + " style='overflow:hidden'  class='form-control  form-control-sm' value='"
  308.                                 + that._quoteattr(adata.data()[0][columnDefs[j].name]) + "'>";
  309.                             data += "<label id='" + columnDefs[j].name + "label"
  310.                                 + "' class='errorLabel'></label>";
  311.                         }
  312.  
  313.                         // Adding readonly-fields
  314.                         if (columnDefs[j].type.indexOf("readonly") >= 0) {
  315.                             data += "<input type='text' readonly  id='"
  316.                                 + columnDefs[j].name
  317.                                 + "' name='"
  318.                                 + columnDefs[j].title
  319.                                 + "' placeholder='"
  320.                                 + columnDefs[j].title
  321.                                 + "' style='overflow:hidden'  class='form-control  form-control-sm' value='"
  322.                                 + adata.data()[0][columnDefs[j].name] + "'>";
  323.                         }
  324.  
  325.                         // Adding select-fields
  326.                         if (columnDefs[j].type.indexOf("select") >= 0) {
  327.                             var options = "";
  328.                             for (var i = 0; i < columnDefs[j].options.length; i++) {
  329.                                 // Assigning the selected value of the <selected> option
  330.                                 if (adata.data()[0][columnDefs[j].name]
  331.                                     .indexOf(columnDefs[j].options[i])>= 0) {
  332.                                     options += "<option value='"
  333.                                         + columnDefs[j].options[i] + "'selected>"
  334.                                         + columnDefs[j].options[i] + "</option>";
  335.                                 } else {
  336.                                     options += "<option value='"
  337.                                         + columnDefs[j].options[i] + "'>"
  338.                                         + columnDefs[j].options[i] + "</option>";
  339.                                 }
  340.                             }
  341.                             data += "<select class='form-control" + (columnDefs[j].select2 ? ' select2' : '') + "' id='" + columnDefs[j].name + "' name='" + columnDefs[j].title + "' " + (columnDefs[j].multiple ? 'multiple' : '') + ">" + options
  342.                                 + "</select>";
  343.                         }
  344.                         data += "</div><div style='clear:both;'></div></div>";
  345.  
  346.                     }
  347.                 }
  348.                 // close form
  349.                 data += "</form>";
  350.  
  351.                 $('#altEditor-modal').on('show.bs.modal', function () {
  352.                     var btns = '<button type="button" data-content="remove" class="btn btn-default" data-dismiss="modal">Close</button>' +
  353.                         '<button type="button" data-content="remove" class="btn btn-primary" id="editRowBtn">Edit</button>';
  354.                     $('#altEditor-modal').find('.modal-title').html('Edit Record');
  355.                     $('#altEditor-modal').find('.modal-body').html(data);
  356.                     $('#altEditor-modal').find('.modal-footer').html(btns);
  357.                 });
  358.  
  359.                 $('#altEditor-modal').modal('show');
  360.                 $('#altEditor-modal input[0]').focus();
  361.  
  362.                 // enable select 2 items
  363.                 for (var j in columnDefs) {
  364.                     if (columnDefs[j].select2) {
  365.                         $("#altEditor-modal").find("select#" + columnDefs[j].name).select2(columnDefs[j].select2);
  366.                     }
  367.                 }
  368.             },
  369.  
  370.             /**
  371.              * Callback for "Edit" button
  372.              */
  373.             _editRowData: function () {
  374.                 var that = this;
  375.                 var dt = this.s.dt;
  376.  
  377.                 // Complete new row data
  378.                 var rowDataArray = {};
  379.  
  380.                 var adata = dt.rows({
  381.                     selected: true
  382.                 });
  383.  
  384.                 // Getting the inputs from the edit-modal
  385.                 $('form[name="altEditor-form"] *').filter(':input').each(function (i) {
  386.                     rowDataArray[$(this).attr('id')] = $(this).val();
  387.                 });
  388.  
  389. console.log(rowDataArray); //DEBUG
  390.  
  391.                 that.onEditRow(that,
  392.                     rowDataArray,
  393.                     function(data,b,c,d,e){ that._editRowCallback(data,b,c,d,e); },
  394.                     function(data){ that._errorCallback(data);
  395.                 });
  396.             },
  397.  
  398.             /**
  399.              * Open Delete Modal for selected row
  400.              *
  401.              * @private
  402.              */
  403.             _openDeleteModal: function () {
  404.                 var that = this;
  405.                 var dt = this.s.dt;
  406.                 var columnDefs = [];
  407.  
  408.                 // Adding attribute IDs and values to object
  409.                 for (var i in dt.context[0].aoColumns) {
  410.                     columnDefs.push({
  411.                         title: dt.context[0].aoColumns[i].sTitle,
  412.                         type: (dt.context[0].aoColumns[i].type ? dt.context[0].aoColumns[i].type : 'text'),
  413.                         name: dt.context[0].aoColumns[i].data ? dt.context[0].aoColumns[i].data : dt.context[0].aoColumns[i].mData
  414.                     });
  415.                 }
  416.                 var adata = dt.rows({
  417.                     selected: true
  418.                 });
  419.  
  420.                 // Building delete-modal
  421.                 var data = "";
  422.  
  423.                 data += "<form name='altEditor-form' role='form'>";
  424.                 for (var j in columnDefs) {
  425.                     if (columnDefs[j].type.indexOf("hidden") >= 0) {
  426.                         data += "<input type='hidden' id='" + columnDefs[j].title + "' value='" + adata.data()[0][columnDefs[j].name] + "'></input>";
  427.                     }
  428.                     else {
  429.                         data += "<div style='margin-left: initial;margin-right: initial;' class='form-group row'><label for='"
  430.                             + that._quoteattr(columnDefs[j].title)
  431.                             + "'>"
  432.                             + columnDefs[j].title
  433.                             + ":  </label> <input  type='hidden'  id='"
  434.                             + that._quoteattr(columnDefs[j].title)
  435.                             + "' name='"
  436.                             + that._quoteattr(columnDefs[j].title)
  437.                             + "' placeholder='"
  438.                             + that._quoteattr(columnDefs[j].title)
  439.                             + "' style='overflow:hidden'  class='form-control' value='"
  440.                             + that._quoteattr(adata.data()[0][columnDefs[j].name]) + "' >"
  441.                             + adata.data()[0][columnDefs[j].name]
  442.                             + "</input></div>";
  443.                     }
  444.                 }
  445.                 // close the form
  446.                 data += "</form>";
  447.  
  448.                 $('#altEditor-modal').on('show.bs.modal', function () {
  449.                     var btns = '<button type="button" data-content="remove" class="btn btn-default" data-dismiss="modal">Close</button>' +
  450.                         '<button type="button"  data-content="remove" class="btn btn-danger" id="deleteRowBtn">Delete</button>';
  451.                     $('#altEditor-modal').find('.modal-title').html('Delete Record');
  452.                     $('#altEditor-modal').find('.modal-body').html(data);
  453.                     $('#altEditor-modal').find('.modal-footer').html(btns);
  454.                 });
  455.  
  456.                 $('#altEditor-modal').modal('show');
  457.                 $('#altEditor-modal input[0]').focus();
  458.             },
  459.  
  460.             /**
  461.              * Callback for "Delete" button
  462.              */
  463.             _deleteRow: function () {
  464.                 var that = this;
  465.                 var dt = this.s.dt;
  466.  
  467.                 var jsonDataArray = {};
  468.  
  469.                 var adata = dt.rows({
  470.                     selected: true
  471.                 });
  472.  
  473.                 // Getting the IDs and Values of the tablerow
  474.                 for (var i = 0; i < dt.context[0].aoColumns.length; i++) {
  475.                     // .data is the attribute name, if any; .idx is the column index, so it should always exists
  476.                     var name = dt.context[0].aoColumns[i].data ? dt.context[0].aoColumns[i].data :
  477.                             dt.context[0].aoColumns[i].mData ? dt.context[0].aoColumns[i].mData :
  478.                             dt.context[0].aoColumns[i].idx;
  479.                     jsonDataArray[name] = adata.data()[0][name];
  480.                 }
  481.                 that.onDeleteRow(that,
  482.                     jsonDataArray,
  483.                     function(data){ that._deleteRowCallback(data); },
  484.                     function(data){ that._errorCallback(data);
  485.                 });
  486.             },
  487.  
  488.             /**
  489.              * Open Add Modal for selected row
  490.              *
  491.              * @private
  492.              */
  493.             _openAddModal: function () {
  494.                 var that = this;
  495.                 var dt = this.s.dt;
  496.                 var columnDefs = [];
  497.  
  498.                 // Adding column attributes to object.
  499.                 for (var i in dt.context[0].aoColumns) {
  500.                     var obj = dt.context[0].aoColumns[i];
  501.                     columnDefs[i] = {
  502.                         title: obj.sTitle,
  503.                         name: (obj.data ? obj.data : obj.mData),
  504.                         type: (obj.type ? obj.type : 'text'),
  505.                         options: (obj.options ? obj.options : []),
  506.                         msg: (obj.errorMsg ? obj.errorMsg : ''),
  507.                         hoverMsg: (obj.hoverMsg ? obj.hoverMsg : ''),
  508.                         pattern: (obj.pattern ? obj.pattern : '.*'),
  509.                         special: (obj.special ? obj.special : ''),
  510.                         unique: (obj.unique ? obj.unique : false),
  511.                         uniqueMsg: (obj.uniqueMsg ? obj.uniqueMsg : ''),
  512.                         maxLength: (obj.maxLength ? obj.maxLength : false),
  513.                         multiple: (obj.multiple ? obj.multiple : false),
  514.                         select2: (obj.select2 ? obj.select2 : false)
  515.                     }
  516.                 }
  517.  
  518.  
  519.                 // Building add-form
  520.                 var data = "";
  521.                 data += "<form name='altEditor-form' role='form'>";
  522.                 for (var j in columnDefs) {
  523.                     if (columnDefs[j].type.indexOf("hidden") >= 0) {
  524.                         // just do nothing for hidden fields!
  525.                     }
  526.                     else {
  527.                         data += "<div style='margin-left: initial;margin-right: initial;' class='form-group row'><div class='col-sm-3 col-md-3 col-lg-3 text-right' style='padding-top:4px;'><label for='"
  528.                             + columnDefs[j].title
  529.                             + "'>"
  530.                             + columnDefs[j].title
  531.                             + ":</label></div><div class='col-sm-8 col-md-8 col-lg-8'>";
  532.  
  533.                         // Adding text-inputs and errorlabels
  534.                         if (columnDefs[j].type.indexOf("text") >= 0) {
  535.                             data += "<input type='"
  536.                                 + that._quoteattr(columnDefs[j].type)
  537.                                 + "' id='"
  538.                                 + that._quoteattr(columnDefs[j].name)
  539.                                 + "'  pattern='"
  540.                                 + that._quoteattr(columnDefs[j].pattern)
  541.                                 + "'  title='"
  542.                                 + that._quoteattr(columnDefs[j].hoverMsg)
  543.                                 + "' name='"
  544.                                 + that._quoteattr(columnDefs[j].title)
  545.                                 + "' placeholder='"
  546.                                 + that._quoteattr(columnDefs[j].title)
  547.                                 + "' data-special='"
  548.                                 + columnDefs[j].special
  549.                                 + "' data-errorMsg='"
  550.                                 + that._quoteattr(columnDefs[j].msg)
  551.                                 + "' data-uniqueMsg='"
  552.                                 + that._quoteattr(columnDefs[j].uniqueMsg)
  553.                                 + "' data-unique='"
  554.                                 + columnDefs[j].unique
  555.                                 + "'"
  556.                                 + (columnDefs[j].maxLength == false ? "" : " maxlength='" + columnDefs[j].maxLength + "'")
  557.                                 + " style='overflow:hidden'  class='form-control  form-control-sm' value=''>";
  558.                             data += "<label id='" + that._quoteattr(columnDefs[j].name) + "label"
  559.                                 + "' class='errorLabel'></label>";
  560.                         }
  561.  
  562.                         // Adding readonly-fields
  563.                         if (columnDefs[j].type.indexOf("readonly") >= 0) {
  564.                             data += "<input type='text' readonly  id='"
  565.                                 + that._quoteattr(columnDefs[j].name)
  566.                                 + "' name='"
  567.                                 + that._quoteattr(columnDefs[j].title)
  568.                                 + "' placeholder='"
  569.                                 + that._quoteattr(columnDefs[j].title)
  570.                                 + "' style='overflow:hidden'  class='form-control  form-control-sm' value=''>";
  571.                         }
  572.  
  573.                         // Adding select-fields
  574.                         if (columnDefs[j].type.indexOf("select") >= 0) {
  575.                             var options = "";
  576.                             for (var i = 0; i < columnDefs[j].options.length; i++) {
  577.                                 options += "<option value='" + that._quoteattr(columnDefs[j].options[i])
  578.                                     + "'>" + columnDefs[j].options[i] + "</option>";
  579.                             }
  580.                             data += "<select class='form-control" + (columnDefs[j].select2 ? ' select2' : '') + "' id='" + that._quoteattr(columnDefs[j].name) + "' name='" + that._quoteattr(columnDefs[j].title) + "' " + (columnDefs[j].multiple ? 'multiple' : '') + ">" + options
  581.                                 + "</select>";
  582.                         }
  583.                         data += "</div><div style='clear:both;'></div></div>";
  584.                     }
  585.                 }
  586.                 data += "</form>";
  587.  
  588.                 $('#altEditor-modal').on('show.bs.modal', function () {
  589.                     var btns = '<button type="button" data-content="remove" class="btn btn-default" data-dismiss="modal">Close</button>' +
  590.                         '<button type="button"  data-content="remove" class="btn btn-primary" id="addRowBtn">Add</button>';
  591.                     $('#altEditor-modal').find('.modal-title').html(
  592.                         'Add Record');
  593.                     $('#altEditor-modal').find('.modal-body')
  594.                         .html(data);
  595.                     $('#altEditor-modal')
  596.                         .find('.modal-footer')
  597.                         .html(btns);
  598.                 });
  599.  
  600.                 $('#altEditor-modal').modal('show');
  601.                 $('#altEditor-modal input[0]').focus();
  602.  
  603.                 // enable select 2 items
  604.                 for (var j in columnDefs) {
  605.                     if (columnDefs[j].select2) {
  606.                         $("#altEditor-modal").find("select#" + columnDefs[j].name).select2(columnDefs[j].select2);
  607.                     }
  608.                 }
  609.             },
  610.  
  611.             /**
  612.              * Callback for "Add" button
  613.              */
  614.             _addRowData: function () {
  615.                 var that = this;
  616.                 var dt = this.s.dt;
  617.  
  618.                 var rowDataArray = {};
  619.  
  620.                 // Getting the inputs from the modal
  621.                 $('form[name="altEditor-form"] *').filter(':input').each(function (i) {
  622.                     rowDataArray[$(this).attr('id')] = $(this).val();
  623.                 });
  624.  
  625. //console.log(rowDataArray); //DEBUG
  626.  
  627.                 that.onAddRow(that,
  628.                     rowDataArray,
  629.                     function(data){ that._addRowCallback(data); },
  630.                     function(data){ that._errorCallback(data);
  631.                 });
  632.  
  633.             },
  634.  
  635.             /**
  636.              * Called after a row has been deleted on server
  637.              */
  638.             _deleteRowCallback: function (response, status, more) {
  639.                     $('#altEditor-modal .modal-body .alert').remove();
  640.  
  641.                     var message = '<div class="alert alert-success" role="alert">' +
  642.                         '<strong>Success!</strong>' +
  643.                         '</div>';
  644.                     $('#altEditor-modal .modal-body').append(message);
  645.  
  646.                     this.s.dt.row({
  647.                         selected : true
  648.                     }).remove();
  649.                     this.s.dt.draw();
  650.  
  651.                     // Disabling submit button
  652.                     $("div#altEditor-modal").find("button#addRowBtn").prop('disabled', true);
  653.                     $("div#altEditor-modal").find("button#editRowBtn").prop('disabled', true);
  654.                     $("div#altEditor-modal").find("button#deleteRowBtn").prop('disabled', true);
  655.             },
  656.  
  657.             /**
  658.              * Called after a row has been inserted on server
  659.              */
  660.             _addRowCallback: function (response, status, more) {
  661.                
  662.                     //TODO should honor dt.ajax().dataSrc
  663.                    
  664.                     var data = JSON.parse(response);
  665.                    
  666.                     $('#altEditor-modal .modal-body .alert').remove();
  667.  
  668.                     var message = '<div class="alert alert-success" role="alert">' +
  669.                         '<strong>Success!</strong>' +
  670.                         '</div>';
  671.                     $('#altEditor-modal .modal-body').append(message);
  672.  
  673.                     this.s.dt.row.add(data).draw(false);
  674.  
  675.                     // Disabling submit button
  676.                     $("div#altEditor-modal").find("button#addRowBtn").prop('disabled', true);
  677.                     $("div#altEditor-modal").find("button#editRowBtn").prop('disabled', true);
  678.                     $("div#altEditor-modal").find("button#deleteRowBtn").prop('disabled', true);
  679.             },
  680.  
  681.             /**
  682.              * Called after a row has been updated on server
  683.              */
  684.             _editRowCallback: function (response, status, more) {
  685.  
  686.                     //TODO should honor dt.ajax().dataSrc
  687.                    
  688.                     var data = JSON.parse(response);
  689.  
  690.                     $('#altEditor-modal .modal-body .alert').remove();
  691.  
  692.                     var message = '<div class="alert alert-success" role="alert">' +
  693.                         '<strong>Success!</strong>' +
  694.                         '</div>';
  695.                     $('#altEditor-modal .modal-body').append(message);
  696.  
  697.                     this.s.dt.row({
  698.                         selected : true
  699.                     }).data(data);
  700.                     this.s.dt.draw();
  701.  
  702.                     // Disabling submit button
  703.                     $("div#altEditor-modal").find("button#addRowBtn").prop('disabled', true);
  704.                     $("div#altEditor-modal").find("button#editRowBtn").prop('disabled', true);
  705.                     $("div#altEditor-modal").find("button#deleteRowBtn").prop('disabled', true);
  706.             },
  707.  
  708.             /**
  709.              * Called after AJAX server returned an error
  710.              */
  711.             _errorCallback: function (response, status, more) {
  712.                     var error = resp;
  713.                     $('#altEditor-modal .modal-body .alert').remove();
  714.                     var errstr = "There was an unknown error!";
  715.                     if (error.responseJSON && error.responseJSON.errors) {
  716.                         errstr = "";
  717.                         for (var key in error.responseJSON.errors) {
  718.                             errstr += error.responseJSON.errors[key][0];
  719.                         }
  720.                     }
  721.                     var message = '<div class="alert alert-danger" role="alert">' +
  722.                         '<strong>Error!</strong> ' + (error.status == null ? "" : 'Response code: ' + error.status) + " " + errstr +
  723.                         '</div>';
  724.  
  725.                     $('#altEditor-modal .modal-body').append(message);
  726.             },
  727.            
  728.             /**
  729.              * Default callback for insertion: mock webservice, always success.
  730.              */
  731.             onAddRow: function(dt, rowdata, success, error) {
  732.                 console.log("Missing AJAX configuration for INSERT");
  733.                 success(rowdata);
  734.             },
  735.  
  736.             /**
  737.              * Default callback for editing: mock webservice, always success.
  738.              */
  739.             onEditRow: function(dt, rowdata, success, error) {
  740.                 console.log("Missing AJAX configuration for UPDATE");
  741.                 success(rowdata);
  742.             },
  743.  
  744.             /**
  745.              * Default callback for deletion: mock webservice, always success.
  746.              */
  747.             onDeleteRow: function(dt, rowdata, success, error) {
  748.                 console.log("Missing AJAX configuration for DELETE");
  749.                 success(rowdata);
  750.             },
  751.  
  752.             /**
  753.              * Validates input
  754.              * @returns {boolean}
  755.              * @private
  756.              */
  757.             _inputValidation: function () {
  758.                 var that = this;
  759.                 var dt = this.s.dt;
  760.                 var isValid = false;
  761.                 var errorcount = 0;
  762.  
  763.                 // Looping through all text fields
  764.                 $('form[name="altEditor-form"] *').filter(':text').each(
  765.                     function (i) {
  766.                         var errorLabel = "#" + $(this).attr("id") + "label";
  767.                         // reset error display
  768.                         $(errorLabel).hide();
  769.                         $(errorLabel).empty();
  770.                         if (!$(this).val().match($(this).attr("pattern"))) {
  771.                             $(errorLabel).html($(this).attr("data-errorMsg"));
  772.                             $(errorLabel).show();
  773.                             errorcount++;
  774.                         }
  775.                         // now check if its should be unique
  776.                         else if ($(this).attr("data-unique") == "true") {
  777.                             // go through each item in this column
  778.                             var colData = dt.column("th:contains('" + $(this).attr("name") + "')").data();
  779.                             var selectedCellData = null;
  780.                             if (dt.row({selected: true}).index() != null)
  781.                                 selectedCellData = dt.cell(dt.row({selected: true}).index(), dt.column("th:contains('" + $(this).attr("name") + "')").index()).data();
  782.                             for (var j in colData) {
  783.                                 // if the element is in the column and its not the selected one then its not unique
  784.                                 if ($(this).val() == colData[j] && colData[j] != selectedCellData) {
  785.                                     $(errorLabel).html($(this).attr("data-uniqueMsg"));
  786.                                     $(errorLabel).show();
  787.                                     errorcount++;
  788.                                 }
  789.                             }
  790.                         }
  791.                     });
  792.  
  793.                 if (errorcount == 0) {
  794.                     isValid = true;
  795.                 }
  796.  
  797.                 return isValid;
  798.             },
  799.  
  800.             /**
  801.              * Sanitizes input for use in HTML
  802.              * @param s
  803.              * @param preserveCR
  804.              * @returns {string}
  805.              * @private
  806.              */
  807.             _quoteattr: function (s, preserveCR) {
  808.                 preserveCR = preserveCR ? '&#13;' : '\n';
  809.                 return ('' + s) /* Forces the conversion to string. */
  810.                     .replace(/&/g, '&amp;') /* This MUST be the 1st replacement. */
  811.                     .replace(/'/g, '&apos;') /* The 4 other predefined entities, required. */
  812.                     .replace(/"/g, '&quot;')
  813.                     .replace(/</g, '&lt;')
  814.                     .replace(/>/g, '&gt;')
  815.                     .replace(/\r\n/g, preserveCR) /* Must be before the next replacement. */
  816.                     .replace(/[\r\n]/g, preserveCR);
  817.             },
  818.         });
  819.  
  820.     /**
  821.      * altEditor version
  822.      *
  823.      * @static
  824.      * @type String
  825.      */
  826.     altEditor.version = '2.0';
  827.  
  828.     /**
  829.      * altEditor defaults
  830.      *
  831.      * @namespace
  832.      */
  833.     altEditor.defaults = {
  834.         /**
  835.          * @type {Boolean} Ask user what they want to do, even for a single
  836.          *       option
  837.          */
  838.         alwaysAsk: false,
  839.  
  840.         /** @type {string|null} What will trigger a focus */
  841.         focus: null, // focus, click, hover
  842.  
  843.         /** @type {column-selector} Columns to provide auto fill for */
  844.         columns: '', // all
  845.  
  846.         /** @type {boolean|null} Update the cells after a drag */
  847.         update: null, // false is editor given, true otherwise
  848.  
  849.         /** @type {DataTable.Editor} Editor instance for automatic submission */
  850.         editor: null
  851.     };
  852.  
  853.     /**
  854.      * Classes used by altEditor that are configurable
  855.      *
  856.      * @namespace
  857.      */
  858.     altEditor.classes = {
  859.         /** @type {String} Class used by the selection button */
  860.         btn: 'btn'
  861.     };
  862.  
  863.     // Attach a listener to the document which listens for DataTables
  864.     // initialisation
  865.     // events so we can automatically initialise
  866.     $(document).on('preInit.dt.altEditor', function (e, settings, json) {
  867.         if (e.namespace !== 'dt') {
  868.             return;
  869.         }
  870.  
  871.         var init = settings.oInit.altEditor;
  872.         var defaults = DataTable.defaults.altEditor;
  873.  
  874.         if (init || defaults) {
  875.             var opts = $.extend({}, init, defaults);
  876.  
  877.             if (init !== false) {
  878.                 new altEditor(settings, opts);
  879.             }
  880.         }
  881.     });
  882.  
  883.     // Alias for access
  884.     DataTable.altEditor = altEditor;
  885.     return altEditor;
  886. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement