Advertisement
Guest User

Untitled

a guest
Mar 20th, 2019
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.94 KB | None | 0 0
  1. (function($) {
  2. var PLUGIN_NS = 'dataTableAuto';
  3.  
  4. var Plugin = function ( target, options ) {
  5. this.$T = $(target);
  6. this._init( target, options );
  7. return this;
  8.  
  9. /** #### OPTIONS #### */
  10. this.options= $.extend(
  11. true, {
  12. DEBUG: false
  13. },
  14. options
  15. );
  16.  
  17. }
  18. /* Init */
  19. Plugin.prototype._init = function ( target, options ) {
  20. this.field = $(target).attr("id").split("_")[1];
  21.  
  22. /* some default values are generated with the table id, but can be changed if needed */
  23. defaultAutoOptions = {
  24. tableName: "table_" + this.field,
  25. formClassName: "form_" + this.field,
  26. jsonFile: "/json/json_" + this.field + ".json",
  27. submitEvtFct: this._submitEvtFct,
  28. clickEvtFct: this._clickEvtFct,
  29. dispFormAjax: false, /* click on the line will change it by a form or make any ajax call to get form if needed */
  30. formAdd: true, /* add some lines allowed */
  31. titreFormNew: ""
  32. }
  33. this.options = $.extend(defaultAutoOptions, Plugin.defaults, options);
  34. if (this.options.formAdd && $("#formNew_" + this.field).length == 0)
  35. this._createFormAdd(target);
  36. this.dataTableAuto = this._dataTableAuto(target);
  37. this.options.clickEvtFct(this);
  38. this.options.submitEvtFct(this);
  39.  
  40. return this;
  41. };
  42.  
  43. /* Default val */
  44. Plugin.defaults = {
  45. events: function(_, callback){ callback([]) }
  46. };
  47.  
  48. /* Auto create the form to add some lines */
  49. Plugin.prototype._createFormAdd = function ( target ) {
  50. var _form = "<form id='formNew_" + this.field + "' class='" + this.options.formClassName + " preventDblClick' method='post'>";
  51. _form += "<h2>" + this.options.titreFormNew + "</h2>";
  52. $(" > thead > tr th", $(this.$T)).each(function(index) {
  53. var attr = $(this).attr("id");
  54. if (typeof attr !== typeof undefined && attr !== false && attr != "col_actions")
  55. _form += "<label>" + $(this).html() + "<br /><input type='text' name='" + attr.split("_")[1] + "' maxlength='" + $(this).data("maxlength") + "' /></label>";
  56. })
  57. _form += "<input type='submit' value='Enregistrer' />";
  58. _form += "</form>";
  59. $(this.$T).before(_form);
  60. }
  61.  
  62. /* Init the datatable */
  63. Plugin.prototype._dataTableAuto = function ( target, options ) {
  64. var _this = this;
  65. var infosTable = this._getInfosColumn(target);
  66. return tableDT = $(this.$T).DataTable({
  67. "ajax": {
  68. 'type': 'GET',
  69. 'url': this.options.jsonFile,
  70. 'data': function ( d ) {
  71. }
  72. },
  73. destroy: true,
  74. info: false,
  75. rowId: "lineID",
  76. 'columnDefs': infosTable.listColumnDef,
  77. "columns": infosTable.listColumn,
  78. 'paging' : false,
  79. "searching": false,
  80. "initComplete": function( settings, json ) {
  81. if (typeof json['eval']!='undefined'){
  82. eval(json['eval']);
  83. }
  84. },
  85. createdRow: function( row, data, dataIndex ) {
  86. _this._setClickableRow(target, row);
  87. }
  88. });
  89. }
  90.  
  91. /* get column data used for datatable */
  92. Plugin.prototype._getInfosColumn = function ( target) {
  93. listColumn = [];
  94. listColumnDef = [];
  95. attr = $(" > thead > tr th:first-child", $(target[0])).attr("id");
  96. if (typeof attr === typeof undefined || attr === false) {
  97. listColumn.push({ "data": "control" });
  98. listColumnDef.push({ className: 'control', targets: 0 });
  99. }
  100. $(" > thead > tr th", $(target[0])).each(function(index) {
  101. if ($(this).attr("id") != undefined) {
  102. listColumnDef.push({ responsivePriority: $(this).attr("id") == "col_buttons" ? 1 : index, targets: index});
  103. if ($(this).hasClass("isDate"))
  104. listColumn.push(
  105. { "data": $(this).attr("id").split("_")[1],
  106. render: function ( data, type, row ) {
  107. return (data.split("-").length == 3 ? moment(data).format("DD/MM/YYYY") : data);
  108. }
  109. }
  110. )
  111. else
  112. listColumn.push({ "data": $(this).attr("id").split("_")[1] })
  113. }
  114. })
  115. return {listColumnDef: listColumnDef, listColumn: listColumn};
  116. }
  117.  
  118. /* On which row add a trigger onclick */
  119. Plugin.prototype._setClickableRow = function (target, row) {
  120. $(" > thead > tr th", $(target[0])).each(function(index) {
  121. if ($(this).hasClass("clickable")) {
  122. $("td:eq(" + index + ")", row).addClass('clickable');
  123. }
  124. if ($(this).attr("id") != undefined)
  125. $("td:eq(" + index + ")", row).addClass($(this).attr("id").split("_")[1]);
  126. })
  127. }
  128.  
  129.  
  130. /* trigger onclick */
  131. Plugin.prototype._clickEvtFct = function ( target, options) {
  132. $(target.$T).on("click", "tr td.clickable, .btDelete", function() {
  133. /* Click on a cell => aff a form to modify */
  134. if ($(this).hasClass("clickable")) {
  135. var theRowObject = target.dataTableAuto.row($(this).closest('tr'));
  136. /* Get the form with ajax request */
  137. if (target.options.dispFormAjax) {
  138. $.getJSON( target.options.jsonFile, {
  139. command: "modLigne",
  140. lineID: lineID
  141. })
  142. .done(function( data ) {
  143. data = data.data[0];
  144. target.dataTableAuto.row(theRowObject).data(data).draw();
  145. /* Not update again the line if the form is displayed */
  146. $("tr#" + data.lineID + " td.clickable").addClass("pausedClick").removeClass("clickable");
  147. });
  148. }
  149. /* auto create the form */
  150. else {
  151. temp = theRowObject.data();
  152. var affForm = true;
  153. var tr = $(this).closest("tr");
  154. var lineID = tr.attr("id").split("_")[1];
  155. $.each(temp, function(item, value) {
  156. var maxLength = $(" > thead > tr th#col_" + item, $(target.$T)).data("maxlength");
  157. if (item != "lineID" && item != "control")
  158. if (item == "actions")
  159. temp[item] = "<button form='mod" + target.field + "_" + lineID + "'>OK</button>";
  160. else if (affForm) {
  161. temp[item] = "<form name='formMod' id='mod" + target.field + "_" + lineID + "' class='form_" + target.field + "'><input type='text' name='" + item + "' value='" + value + "' maxlength='" + maxLength + "' /></form>";
  162. affForm = false;
  163. }
  164. else
  165. temp[item] = "<input type='text' name='" + item + "' value='" + value + "' form='mod" + target.field + "_" + lineID + "' maxlength='" + maxLength + "' />";
  166. })
  167. target.dataTableAuto.row(theRowObject).data(temp).draw();
  168. $("td.clickable", tr).addClass("pausedClick").removeClass("clickable");
  169. }
  170. }
  171. /* bouton to delete the line */
  172. else if ($(this).hasClass("btDelete")) {
  173. var goAction = true;
  174. var tr = $(this).closest("tr");
  175. var lineID = tr.attr("id").split("_")[1];
  176. if(typeof $(this).data("message")!='undefined' && !confirm($(this).data("message")))
  177. return false;
  178. $.getJSON( target.options.jsonFile, {command: 'suppLine', lineID: lineID})
  179. .done(function( datas ) {
  180. /* Actions to do when succeed */
  181. if (datas.success)
  182. target.dataTableAuto.row('#' + tr.attr("id")).remove().draw();
  183. });
  184. }
  185. })
  186. }
  187.  
  188. /* trigger submit form to add or update line */
  189. Plugin.prototype._submitEvtFct = function ( target) {
  190. $("body").on("submit", "form." + target.options.formClassName, function(e) {
  191. e.preventDefault();
  192. $.getJSON( target.options.jsonFile, $(this).serialize() + "&command=saveData&lineID=" + ($(this).closest("tr").length > 0 ? $(this).closest("tr").attr("id").split("_")[1] : 0))
  193. .done(function( datas ) {
  194. data = datas.data[0];
  195. var _tr = $("tr#" + data.lineID);
  196. if (_tr.length > 0) {
  197. target.dataTableAuto.row($("tr#" + data.lineID).index()).data(data).draw();
  198. /* Autorize the click for display one more time the update form */
  199. $("tr#" + data.lineID + " td.pausedClick").addClass("clickable").removeClass("pausedClick");
  200. }
  201. else {
  202. target.dataTableAuto.row.add( data ).node().id = data.lineID;
  203. target.dataTableAuto.draw();
  204. }
  205. if(typeof datas['eval']!='undefined')eval(datas['eval']);
  206. });
  207. })
  208. }
  209.  
  210. Plugin.prototype.DWARN = function () {
  211. this.DEBUG && console.warn( arguments );
  212. }
  213.  
  214.  
  215. $.fn[ PLUGIN_NS ] = function( methodOrOptions ) {
  216. if (!$(this).length) {
  217. return $(this);
  218. }
  219. var instance = $(this).data(PLUGIN_NS);
  220.  
  221. if ( instance
  222. && methodOrOptions.indexOf('_') != 0
  223. && instance[ methodOrOptions ]
  224. && typeof( instance[ methodOrOptions ] ) == 'function' ) {
  225.  
  226. return instance[ methodOrOptions ](this, Array.prototype.slice.call( arguments, 1 ) );
  227.  
  228.  
  229. } else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) {
  230.  
  231. return this.each(function() {
  232. instance = new Plugin( $(this), methodOrOptions );
  233. $(this).data( PLUGIN_NS, instance );
  234. })
  235.  
  236. // CASE: method called before init
  237. } else if ( !instance ) {
  238. $.error( 'Plugin must be initialised before using method: ' + methodOrOptions );
  239.  
  240. // CASE: invalid method
  241. } else if ( methodOrOptions.indexOf('_') == 0 ) {
  242. $.error( 'Method ' + methodOrOptions + ' is private!' );
  243. } else {
  244. $.error( 'Method ' + methodOrOptions + ' does not exist.' );
  245. }
  246. };
  247.  
  248. })(jQuery);
  249.  
  250. <table id="table_categorie">
  251. <thead>
  252. <th></th>
  253. <th id="col_categorieCode" class="clickable" data-maxlength="10">Code</th>
  254. <th id="col_categorieLib" class="clickable" data-maxlength="100">libellé</th>
  255. <th id="col_actions"></th>
  256. </thead>
  257. <tbody>
  258. </tbody>
  259. </table>
  260.  
  261. var tableCategorie = $("table#table_categorie").dataTableAuto({titreFormNew: "Nouvelle catégorie"});
  262.  
  263. "data": [
  264. {
  265.  
  266. "control": "",
  267. "lineID": "categorie_1",
  268. "categorieClientCode": "123",
  269. "categorieClientLib": "categorie 1",
  270. "codeCompta": "",
  271. "actions": "<button class="btSupp" data-message="Are you sure to delete this categorie ?"></button>"
  272. }
  273. ,
  274. {
  275. "control": "",
  276. "lineID": "categorie_2",
  277. "categorieClientCode": "124",
  278. "categorieClientLib": "categorie 2",
  279. "codeCompta": "",
  280. "actions": "<button class="btSupp" data-toggle="tootltip" data-placement="top" data-message="Are you sure to delete this categorie ?"></button>"
  281. }
  282. ]
  283.  
  284. {"success":"true","msg":"the line was deleted"}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement