yii.gridView.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. /**
  2. * Yii GridView widget.
  3. *
  4. * This is the JavaScript widget used by the yii\grid\GridView widget.
  5. *
  6. * @link http://www.yiiframework.com/
  7. * @copyright Copyright (c) 2008 Yii Software LLC
  8. * @license http://www.yiiframework.com/license/
  9. * @author Qiang Xue <qiang.xue@gmail.com>
  10. * @since 2.0
  11. */
  12. (function ($) {
  13. $.fn.yiiGridView = function (method) {
  14. if (methods[method]) {
  15. return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
  16. } else if (typeof method === 'object' || !method) {
  17. return methods.init.apply(this, arguments);
  18. } else {
  19. $.error('Method ' + method + ' does not exist in jQuery.yiiGridView');
  20. return false;
  21. }
  22. };
  23. var defaults = {
  24. filterUrl: undefined,
  25. filterSelector: undefined,
  26. filterOnFocusOut: true
  27. };
  28. var gridData = {};
  29. var gridEvents = {
  30. /**
  31. * beforeFilter event is triggered before filtering the grid.
  32. * The signature of the event handler should be:
  33. * function (event)
  34. * where
  35. * - event: an Event object.
  36. *
  37. * If the handler returns a boolean false, it will stop filter form submission after this event. As
  38. * a result, afterFilter event will not be triggered.
  39. */
  40. beforeFilter: 'beforeFilter',
  41. /**
  42. * afterFilter event is triggered after filtering the grid and filtered results are fetched.
  43. * The signature of the event handler should be:
  44. * function (event)
  45. * where
  46. * - event: an Event object.
  47. */
  48. afterFilter: 'afterFilter'
  49. };
  50. /**
  51. * Used for storing active event handlers and removing them later.
  52. * The structure of single event handler is:
  53. *
  54. * {
  55. * gridViewId: {
  56. * type: {
  57. * event: '...',
  58. * selector: '...'
  59. * }
  60. * }
  61. * }
  62. *
  63. * Used types:
  64. *
  65. * - filter, used for filtering grid with elements found by filterSelector
  66. * - checkRow, used for checking single row
  67. * - checkAllRows, used for checking all rows with according "Check all" checkbox
  68. *
  69. * event is the name of event, for example: 'change.yiiGridView'
  70. * selector is a jQuery selector for finding elements
  71. *
  72. * @type {{}}
  73. */
  74. var gridEventHandlers = {};
  75. var methods = {
  76. init: function (options) {
  77. return this.each(function () {
  78. var $e = $(this);
  79. var settings = $.extend({}, defaults, options || {});
  80. var id = $e.attr('id');
  81. if (gridData[id] === undefined) {
  82. gridData[id] = {};
  83. }
  84. gridData[id] = $.extend(gridData[id], {settings: settings});
  85. var filterEvents = 'change.yiiGridView keydown.yiiGridView';
  86. var enterPressed = false;
  87. initEventHandler($e, 'filter', filterEvents, settings.filterSelector, function (event) {
  88. if (event.type === 'keydown') {
  89. if (event.keyCode !== 13) {
  90. return; // only react to enter key
  91. } else {
  92. enterPressed = true;
  93. }
  94. } else {
  95. // prevent processing for both keydown and change events
  96. if (enterPressed) {
  97. enterPressed = false;
  98. return;
  99. }
  100. }
  101. if (!settings.filterOnFocusOut && event.type !== 'keydown') {
  102. return false;
  103. }
  104. methods.applyFilter.apply($e);
  105. return false;
  106. });
  107. });
  108. },
  109. applyFilter: function () {
  110. var $grid = $(this);
  111. var settings = gridData[$grid.attr('id')].settings;
  112. var data = {};
  113. $.each($(settings.filterSelector).serializeArray(), function () {
  114. if (!(this.name in data)) {
  115. data[this.name] = [];
  116. }
  117. data[this.name].push(this.value);
  118. });
  119. var namesInFilter = Object.keys(data);
  120. $.each(yii.getQueryParams(settings.filterUrl), function (name, value) {
  121. if (namesInFilter.indexOf(name) === -1 && namesInFilter.indexOf(name.replace(/\[\d*\]$/, '')) === -1) {
  122. if (!$.isArray(value)) {
  123. value = [value];
  124. }
  125. if (!(name in data)) {
  126. data[name] = value;
  127. } else {
  128. $.each(value, function (i, val) {
  129. if ($.inArray(val, data[name])) {
  130. data[name].push(val);
  131. }
  132. });
  133. }
  134. }
  135. });
  136. var pos = settings.filterUrl.indexOf('?');
  137. var url = pos < 0 ? settings.filterUrl : settings.filterUrl.substring(0, pos);
  138. var hashPos = settings.filterUrl.indexOf('#');
  139. if (pos >= 0 && hashPos >= 0) {
  140. url += settings.filterUrl.substring(hashPos);
  141. }
  142. $grid.find('form.gridview-filter-form').remove();
  143. var $form = $('<form/>', {
  144. action: url,
  145. method: 'get',
  146. 'class': 'gridview-filter-form',
  147. style: 'display:none',
  148. 'data-pjax': ''
  149. }).appendTo($grid);
  150. $.each(data, function (name, values) {
  151. $.each(values, function (index, value) {
  152. $form.append($('<input/>').attr({type: 'hidden', name: name, value: value}));
  153. });
  154. });
  155. var event = $.Event(gridEvents.beforeFilter);
  156. $grid.trigger(event);
  157. if (event.result === false) {
  158. return;
  159. }
  160. $form.submit();
  161. $grid.trigger(gridEvents.afterFilter);
  162. },
  163. setSelectionColumn: function (options) {
  164. var $grid = $(this);
  165. var id = $(this).attr('id');
  166. if (gridData[id] === undefined) {
  167. gridData[id] = {};
  168. }
  169. gridData[id].selectionColumn = options.name;
  170. if (!options.multiple || !options.checkAll) {
  171. return;
  172. }
  173. var checkAll = "#" + id + " input[name='" + options.checkAll + "']";
  174. var inputs = options['class'] ? "input." + options['class'] : "input[name='" + options.name + "']";
  175. var inputsEnabled = "#" + id + " " + inputs + ":enabled";
  176. initEventHandler($grid, 'checkAllRows', 'click.yiiGridView', checkAll, function () {
  177. $grid.find(inputs + ":enabled").prop('checked', this.checked).change();
  178. });
  179. initEventHandler($grid, 'checkRow', 'click.yiiGridView', inputsEnabled, function () {
  180. var all = $grid.find(inputs).length == $grid.find(inputs + ":checked").length;
  181. $grid.find("input[name='" + options.checkAll + "']").prop('checked', all).change();
  182. });
  183. },
  184. getSelectedRows: function () {
  185. var $grid = $(this);
  186. var data = gridData[$grid.attr('id')];
  187. var keys = [];
  188. if (data.selectionColumn) {
  189. $grid.find("input[name='" + data.selectionColumn + "']:checked").each(function () {
  190. keys.push($(this).parent().closest('tr').data('key'));
  191. });
  192. }
  193. return keys;
  194. },
  195. destroy: function () {
  196. var events = ['.yiiGridView', gridEvents.beforeFilter, gridEvents.afterFilter].join(' ');
  197. this.off(events);
  198. var id = $(this).attr('id');
  199. $.each(gridEventHandlers[id], function (type, data) {
  200. $(document).off(data.event, data.selector);
  201. });
  202. delete gridData[id];
  203. return this;
  204. },
  205. data: function () {
  206. var id = $(this).attr('id');
  207. return gridData[id];
  208. }
  209. };
  210. /**
  211. * Used for attaching event handler and prevent of duplicating them. With each call previously attached handler of
  212. * the same type is removed even selector was changed.
  213. * @param {jQuery} $gridView According jQuery grid view element
  214. * @param {string} type Type of the event which acts like a key
  215. * @param {string} event Event name, for example 'change.yiiGridView'
  216. * @param {string} selector jQuery selector
  217. * @param {function} callback The actual function to be executed with this event
  218. */
  219. function initEventHandler($gridView, type, event, selector, callback) {
  220. var id = $gridView.attr('id');
  221. var prevHandler = gridEventHandlers[id];
  222. if (prevHandler !== undefined && prevHandler[type] !== undefined) {
  223. var data = prevHandler[type];
  224. $(document).off(data.event, data.selector);
  225. }
  226. if (prevHandler === undefined) {
  227. gridEventHandlers[id] = {};
  228. }
  229. $(document).on(event, selector, callback);
  230. gridEventHandlers[id][type] = {event: event, selector: selector};
  231. }
  232. })(window.jQuery);