bootstrap-table-filter-control.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889
  1. /**
  2. * @author: Dennis Hernández
  3. * @webSite: http://djhvscf.github.io/Blog
  4. * @version: v2.2.0
  5. */
  6. const Utils = $.fn.bootstrapTable.utils
  7. const UtilsFilterControl = {
  8. getOptionsFromSelectControl (selectControl) {
  9. return selectControl.get(selectControl.length - 1).options
  10. },
  11. getControlContainer () {
  12. if (UtilsFilterControl.bootstrapTableInstance.options.filterControlContainer) {
  13. return $(`${UtilsFilterControl.bootstrapTableInstance.options.filterControlContainer}`)
  14. }
  15. return UtilsFilterControl.getCurrentHeader(UtilsFilterControl.bootstrapTableInstance)
  16. },
  17. getSearchControls (scope) {
  18. const header = UtilsFilterControl.getControlContainer()
  19. const searchControls = UtilsFilterControl.getCurrentSearchControls(scope)
  20. return header.find(searchControls)
  21. },
  22. hideUnusedSelectOptions (selectControl, uniqueValues) {
  23. const options = UtilsFilterControl.getOptionsFromSelectControl(
  24. selectControl
  25. )
  26. for (let i = 0; i < options.length; i++) {
  27. if (options[i].value !== '') {
  28. if (!uniqueValues.hasOwnProperty(options[i].value)) {
  29. selectControl
  30. .find(Utils.sprintf('option[value=\'%s\']', options[i].value))
  31. .hide()
  32. } else {
  33. selectControl
  34. .find(Utils.sprintf('option[value=\'%s\']', options[i].value))
  35. .show()
  36. }
  37. }
  38. }
  39. },
  40. addOptionToSelectControl (selectControl, _value, text, selected) {
  41. const value = $.trim(_value)
  42. const $selectControl = $(selectControl.get(selectControl.length - 1))
  43. if (
  44. !UtilsFilterControl.existOptionInSelectControl(selectControl, value)
  45. ) {
  46. const option = $(`<option value="${value}">${text}</option>`)
  47. if (value === selected) {
  48. option.attr('selected', true)
  49. }
  50. $selectControl.append(option)
  51. }
  52. },
  53. sortSelectControl (selectControl, orderBy) {
  54. const $selectControl = $(selectControl.get(selectControl.length - 1))
  55. const $opts = $selectControl.find('option:gt(0)')
  56. $opts.sort((a, b) => {
  57. return Utils.sort(a.textContent, b.textContent, orderBy === 'desc' ? -1 : 1)
  58. })
  59. $selectControl.find('option:gt(0)').remove()
  60. $selectControl.append($opts)
  61. },
  62. existOptionInSelectControl (selectControl, value) {
  63. const options = UtilsFilterControl.getOptionsFromSelectControl(
  64. selectControl
  65. )
  66. for (let i = 0; i < options.length; i++) {
  67. if (options[i].value === value.toString()) {
  68. // The value is not valid to add
  69. return true
  70. }
  71. }
  72. // If we get here, the value is valid to add
  73. return false
  74. },
  75. fixHeaderCSS ({$tableHeader}) {
  76. $tableHeader.css('height', '77px')
  77. },
  78. getCurrentHeader ({$header, options, $tableHeader}) {
  79. let header = $header
  80. if (options.height) {
  81. header = $tableHeader
  82. }
  83. return header
  84. },
  85. getCurrentSearchControls ({options}) {
  86. let searchControls = 'select, input'
  87. if (options.height) {
  88. searchControls = 'table select, table input'
  89. }
  90. return searchControls
  91. },
  92. getCursorPosition (el) {
  93. if (Utils.isIEBrowser()) {
  94. if ($(el).is('input[type=text]')) {
  95. let pos = 0
  96. if ('selectionStart' in el) {
  97. pos = el.selectionStart
  98. } else if ('selection' in document) {
  99. el.focus()
  100. const Sel = document.selection.createRange()
  101. const SelLength = document.selection.createRange().text.length
  102. Sel.moveStart('character', -el.value.length)
  103. pos = Sel.text.length - SelLength
  104. }
  105. return pos
  106. }
  107. return -1
  108. }
  109. return -1
  110. },
  111. setCursorPosition (el) {
  112. $(el).val(el.value)
  113. },
  114. copyValues (that) {
  115. const searchControls = UtilsFilterControl.getSearchControls(that)
  116. that.options.valuesFilterControl = []
  117. searchControls.each(function () {
  118. that.options.valuesFilterControl.push({
  119. field: $(this)
  120. .closest('[data-field]')
  121. .data('field'),
  122. value: $(this).val(),
  123. position: UtilsFilterControl.getCursorPosition($(this).get(0)),
  124. hasFocus: $(this).is(':focus')
  125. })
  126. })
  127. },
  128. setValues (that) {
  129. let field = null
  130. let result = []
  131. const searchControls = UtilsFilterControl.getSearchControls(that)
  132. if (that.options.valuesFilterControl.length > 0) {
  133. // Callback to apply after settings fields values
  134. let fieldToFocusCallback = null
  135. searchControls.each(function (index, ele) {
  136. field = $(this)
  137. .closest('[data-field]')
  138. .data('field')
  139. result = that.options.valuesFilterControl.filter(valueObj => valueObj.field === field)
  140. if (result.length > 0) {
  141. $(this).val(result[0].value)
  142. if (result[0].hasFocus) {
  143. // set callback if the field had the focus.
  144. fieldToFocusCallback = ((fieldToFocus, carretPosition) => {
  145. // Closure here to capture the field and cursor position
  146. const closedCallback = () => {
  147. fieldToFocus.focus()
  148. UtilsFilterControl.setCursorPosition(fieldToFocus, carretPosition)
  149. }
  150. return closedCallback
  151. })($(this).get(0), result[0].position)
  152. }
  153. }
  154. })
  155. // Callback call.
  156. if (fieldToFocusCallback !== null) {
  157. fieldToFocusCallback()
  158. }
  159. }
  160. },
  161. collectBootstrapCookies () {
  162. const cookies = []
  163. const foundCookies = document.cookie.match(/(?:bs.table.)(\w*)/g)
  164. if (foundCookies) {
  165. $.each(foundCookies, (i, _cookie) => {
  166. let cookie = _cookie
  167. if (/./.test(cookie)) {
  168. cookie = cookie.split('.').pop()
  169. }
  170. if ($.inArray(cookie, cookies) === -1) {
  171. cookies.push(cookie)
  172. }
  173. })
  174. return cookies
  175. }
  176. },
  177. escapeID (id) {
  178. // eslint-disable-next-line no-useless-escape
  179. return String(id).replace(/([:.\[\],])/g, '\\$1')
  180. },
  181. isColumnSearchableViaSelect ({filterControl, searchable}) {
  182. return filterControl &&
  183. filterControl.toLowerCase() === 'select' &&
  184. searchable
  185. },
  186. isFilterDataNotGiven ({filterData}) {
  187. return filterData === undefined ||
  188. filterData.toLowerCase() === 'column'
  189. },
  190. hasSelectControlElement (selectControl) {
  191. return selectControl && selectControl.length > 0
  192. },
  193. initFilterSelectControls (that) {
  194. const data = that.data
  195. const z = that.options.pagination
  196. ? that.options.sidePagination === 'server'
  197. ? that.pageTo
  198. : that.options.totalRows
  199. : that.pageTo
  200. $.each(that.header.fields, (j, field) => {
  201. const column = that.columns[that.fieldsColumnsIndex[field]]
  202. const selectControl = UtilsFilterControl.getControlContainer().find(`.bootstrap-table-filter-control-${UtilsFilterControl.escapeID(column.field)}`)
  203. if (
  204. UtilsFilterControl.isColumnSearchableViaSelect(column) &&
  205. UtilsFilterControl.isFilterDataNotGiven(column) &&
  206. UtilsFilterControl.hasSelectControlElement(selectControl)
  207. ) {
  208. if (selectControl.get(selectControl.length - 1).options.length === 0) {
  209. // Added the default option
  210. UtilsFilterControl.addOptionToSelectControl(selectControl, '', column.filterControlPlaceholder, column.filterDefault)
  211. }
  212. const uniqueValues = {}
  213. for (let i = 0; i < z; i++) {
  214. // Added a new value
  215. const fieldValue = data[i][field]
  216. let formattedValue = Utils.calculateObjectValue(that.header, that.header.formatters[j], [fieldValue, data[i], i], fieldValue)
  217. if (column.filterDataCollector) {
  218. formattedValue = Utils.calculateObjectValue(that.header, column.filterDataCollector, [fieldValue, data[i], formattedValue], formattedValue)
  219. }
  220. if (typeof formattedValue === 'object' && formattedValue !== null) {
  221. formattedValue.forEach((value) => {
  222. UtilsFilterControl.addOptionToSelectControl(selectControl, value, value, column.filterDefault)
  223. })
  224. continue
  225. }
  226. UtilsFilterControl.addOptionToSelectControl(selectControl, formattedValue, formattedValue, column.filterDefault)
  227. }
  228. UtilsFilterControl.sortSelectControl(selectControl, column.filterOrderBy)
  229. if (that.options.hideUnusedSelectOptions) {
  230. UtilsFilterControl.hideUnusedSelectOptions(selectControl, uniqueValues)
  231. }
  232. }
  233. })
  234. that.trigger('created-controls')
  235. },
  236. getFilterDataMethod (objFilterDataMethod, searchTerm) {
  237. const keys = Object.keys(objFilterDataMethod)
  238. for (let i = 0; i < keys.length; i++) {
  239. if (keys[i] === searchTerm) {
  240. return objFilterDataMethod[searchTerm]
  241. }
  242. }
  243. return null
  244. },
  245. createControls (that, header) {
  246. let addedFilterControl = false
  247. let isVisible
  248. let html
  249. $.each(that.columns, (i, column) => {
  250. html = []
  251. if (!column.visible) {
  252. return
  253. }
  254. if (!column.filterControl && !that.options.filterControlContainer) {
  255. html.push('<div class="no-filter-control"></div>')
  256. } else if (that.options.filterControlContainer) {
  257. const $filterControl = $(`.bootstrap-table-filter-control-${column.field}`)
  258. const placeholder = column.filterControlPlaceholder ? column.filterControlPlaceholder : ''
  259. $filterControl.attr('placeholder', placeholder)
  260. $filterControl.val(column.filterDefault)
  261. $filterControl.attr('data-field', column.field)
  262. addedFilterControl = true
  263. } else {
  264. const nameControl = column.filterControl.toLowerCase()
  265. html.push('<div class="filter-control">')
  266. addedFilterControl = true
  267. if (column.searchable && that.options.filterTemplate[nameControl]) {
  268. html.push(
  269. that.options.filterTemplate[nameControl](
  270. that,
  271. column.field,
  272. column.filterControlPlaceholder
  273. ? column.filterControlPlaceholder
  274. : '',
  275. column.filterDefault
  276. )
  277. )
  278. }
  279. }
  280. if (!column.filterControl && '' !== column.filterDefault && 'undefined' !== typeof column.filterDefault) {
  281. if ($.isEmptyObject(that.filterColumnsPartial)) {
  282. that.filterColumnsPartial = {}
  283. }
  284. that.filterColumnsPartial[column.field] = column.filterDefault
  285. }
  286. $.each(header.children().children(), (i, tr) => {
  287. const $tr = $(tr)
  288. if ($tr.data('field') === column.field) {
  289. $tr.find('.fht-cell').append(html.join(''))
  290. return false
  291. }
  292. })
  293. if (
  294. column.filterData !== undefined &&
  295. column.filterData.toLowerCase() !== 'column'
  296. ) {
  297. const filterDataType = UtilsFilterControl.getFilterDataMethod(
  298. /* eslint-disable no-use-before-define */
  299. filterDataMethods,
  300. column.filterData.substring(0, column.filterData.indexOf(':'))
  301. )
  302. let filterDataSource
  303. let selectControl
  304. if (filterDataType !== null) {
  305. filterDataSource = column.filterData.substring(
  306. column.filterData.indexOf(':') + 1,
  307. column.filterData.length
  308. )
  309. selectControl = UtilsFilterControl.getControlContainer().find(`.bootstrap-table-filter-control-${UtilsFilterControl.escapeID(column.field)}`)
  310. UtilsFilterControl.addOptionToSelectControl(selectControl, '', column.filterControlPlaceholder, column.filterDefault)
  311. filterDataType(filterDataSource, selectControl, column.filterDefault)
  312. } else {
  313. throw new SyntaxError(
  314. 'Error. You should use any of these allowed filter data methods: var, json, url.' +
  315. ' Use like this: var: {key: "value"}'
  316. )
  317. }
  318. let variableValues
  319. let key
  320. // eslint-disable-next-line default-case
  321. switch (filterDataType) {
  322. case 'url':
  323. $.ajax({
  324. url: filterDataSource,
  325. dataType: 'json',
  326. success (data) {
  327. // eslint-disable-next-line guard-for-in
  328. for (const key in data) {
  329. UtilsFilterControl.addOptionToSelectControl(selectControl, key, data[key], column.filterDefault)
  330. }
  331. UtilsFilterControl.sortSelectControl(selectControl, column.filterOrderBy)
  332. }
  333. })
  334. break
  335. case 'var':
  336. variableValues = window[filterDataSource]
  337. // eslint-disable-next-line guard-for-in
  338. for (key in variableValues) {
  339. UtilsFilterControl.addOptionToSelectControl(selectControl, key, variableValues[key], column.filterDefault)
  340. }
  341. UtilsFilterControl.sortSelectControl(selectControl, column.filterOrderBy)
  342. break
  343. case 'jso':
  344. variableValues = JSON.parse(filterDataSource)
  345. // eslint-disable-next-line guard-for-in
  346. for (key in variableValues) {
  347. UtilsFilterControl.addOptionToSelectControl(selectControl, key, variableValues[key], column.filterDefault)
  348. }
  349. UtilsFilterControl.sortSelectControl(selectControl, column.filterOrderBy)
  350. break
  351. }
  352. }
  353. })
  354. if (addedFilterControl) {
  355. UtilsFilterControl.getControlContainer().off('keyup', 'input').on('keyup', 'input', ({currentTarget, keyCode}, obj) => {
  356. // Simulate enter key action from clear button
  357. keyCode = obj ? obj.keyCode : keyCode
  358. if (that.options.searchOnEnterKey && keyCode !== 13) {
  359. return
  360. }
  361. if ($.inArray(keyCode, [37, 38, 39, 40]) > -1) {
  362. return
  363. }
  364. const $currentTarget = $(currentTarget)
  365. if ($currentTarget.is(':checkbox') || $currentTarget.is(':radio')) {
  366. return
  367. }
  368. clearTimeout(currentTarget.timeoutId || 0)
  369. currentTarget.timeoutId = setTimeout(() => {
  370. that.onColumnSearch({currentTarget, keyCode})
  371. }, that.options.searchTimeOut)
  372. })
  373. UtilsFilterControl.getControlContainer().off('change', 'select').on('change', 'select', ({currentTarget, keyCode}) => {
  374. if (that.options.searchOnEnterKey && keyCode !== 13) {
  375. return
  376. }
  377. if ($.inArray(keyCode, [37, 38, 39, 40]) > -1) {
  378. return
  379. }
  380. clearTimeout(currentTarget.timeoutId || 0)
  381. currentTarget.timeoutId = setTimeout(() => {
  382. that.onColumnSearch({currentTarget, keyCode})
  383. }, that.options.searchTimeOut)
  384. })
  385. header.off('mouseup', 'input').on('mouseup', 'input', ({currentTarget, keyCode}) => {
  386. const $input = $(currentTarget)
  387. const oldValue = $input.val()
  388. if (oldValue === '') {
  389. return
  390. }
  391. setTimeout(() => {
  392. const newValue = $input.val()
  393. if (newValue === '') {
  394. clearTimeout(currentTarget.timeoutId || 0)
  395. currentTarget.timeoutId = setTimeout(() => {
  396. that.onColumnSearch({currentTarget, keyCode})
  397. }, that.options.searchTimeOut)
  398. }
  399. }, 1)
  400. })
  401. if (UtilsFilterControl.getControlContainer().find('.date-filter-control').length > 0) {
  402. $.each(that.columns, (i, {filterControl, field, filterDatepickerOptions}) => {
  403. if (
  404. filterControl !== undefined &&
  405. filterControl.toLowerCase() === 'datepicker'
  406. ) {
  407. UtilsFilterControl.getControlContainer()
  408. .find(
  409. `.date-filter-control.bootstrap-table-filter-control-${field}`
  410. )
  411. .datepicker(filterDatepickerOptions)
  412. .on('changeDate', ({currentTarget, keyCode}) => {
  413. clearTimeout(currentTarget.timeoutId || 0)
  414. currentTarget.timeoutId = setTimeout(() => {
  415. that.onColumnSearch({currentTarget, keyCode})
  416. }, that.options.searchTimeOut)
  417. })
  418. }
  419. })
  420. }
  421. if (that.options.sidePagination !== 'server') {
  422. that.triggerSearch()
  423. }
  424. } else {
  425. UtilsFilterControl.getControlContainer().find('.filterControl').hide()
  426. }
  427. },
  428. getDirectionOfSelectOptions (_alignment) {
  429. const alignment = _alignment === undefined ? 'left' : _alignment.toLowerCase()
  430. switch (alignment) {
  431. case 'left':
  432. return 'ltr'
  433. case 'right':
  434. return 'rtl'
  435. case 'auto':
  436. return 'auto'
  437. default:
  438. return 'ltr'
  439. }
  440. }
  441. }
  442. const filterDataMethods = {
  443. var (filterDataSource, selectControl, filterOrderBy, selected) {
  444. const variableValues = window[filterDataSource]
  445. // eslint-disable-next-line guard-for-in
  446. for (const key in variableValues) {
  447. UtilsFilterControl.addOptionToSelectControl(selectControl, key, variableValues[key], selected)
  448. }
  449. UtilsFilterControl.sortSelectControl(selectControl, filterOrderBy)
  450. },
  451. url (filterDataSource, selectControl, filterOrderBy, selected) {
  452. $.ajax({
  453. url: filterDataSource,
  454. dataType: 'json',
  455. success (data) {
  456. // eslint-disable-next-line guard-for-in
  457. for (const key in data) {
  458. UtilsFilterControl.addOptionToSelectControl(selectControl, key, data[key], selected)
  459. }
  460. UtilsFilterControl.sortSelectControl(selectControl, filterOrderBy)
  461. }
  462. })
  463. },
  464. json (filterDataSource, selectControl, filterOrderBy, selected) {
  465. const variableValues = JSON.parse(filterDataSource)
  466. // eslint-disable-next-line guard-for-in
  467. for (const key in variableValues) {
  468. UtilsFilterControl.addOptionToSelectControl(selectControl, key, variableValues[key], selected)
  469. }
  470. UtilsFilterControl.sortSelectControl(selectControl, filterOrderBy)
  471. }
  472. }
  473. $.extend($.fn.bootstrapTable.defaults, {
  474. filterControl: false,
  475. onColumnSearch (field, text) {
  476. return false
  477. },
  478. onCreatedControls () {
  479. return true
  480. },
  481. alignmentSelectControlOptions: undefined,
  482. filterTemplate: {
  483. input (that, field, placeholder, value) {
  484. return Utils.sprintf(
  485. '<input type="text" class="form-control bootstrap-table-filter-control-%s" style="width: 100%;" placeholder="%s" value="%s">',
  486. field,
  487. 'undefined' === typeof placeholder ? '' : placeholder,
  488. 'undefined' === typeof value ? '' : value
  489. )
  490. },
  491. select ({options}, field) {
  492. return Utils.sprintf(
  493. '<select class="form-control bootstrap-table-filter-control-%s" style="width: 100%;" dir="%s"></select>',
  494. field,
  495. UtilsFilterControl.getDirectionOfSelectOptions(
  496. options.alignmentSelectControlOptions
  497. )
  498. )
  499. },
  500. datepicker (that, field, value) {
  501. return Utils.sprintf(
  502. '<input type="text" class="form-control date-filter-control bootstrap-table-filter-control-%s" style="width: 100%;" value="%s">',
  503. field,
  504. 'undefined' === typeof value ? '' : value
  505. )
  506. }
  507. },
  508. disableControlWhenSearch: false,
  509. searchOnEnterKey: false,
  510. // internal variables
  511. valuesFilterControl: []
  512. })
  513. $.extend($.fn.bootstrapTable.columnDefaults, {
  514. filterControl: undefined,
  515. filterDataCollector: undefined,
  516. filterData: undefined,
  517. filterDatepickerOptions: undefined,
  518. filterStrictSearch: false,
  519. filterStartsWithSearch: false,
  520. filterControlPlaceholder: '',
  521. filterDefault: '',
  522. filterOrderBy: 'asc' // asc || desc
  523. })
  524. $.extend($.fn.bootstrapTable.Constructor.EVENTS, {
  525. 'column-search.bs.table': 'onColumnSearch',
  526. 'created-controls.bs.table': 'onCreatedControls'
  527. })
  528. $.extend($.fn.bootstrapTable.defaults.icons, {
  529. clear: {
  530. bootstrap3: 'glyphicon-trash icon-clear'
  531. }[$.fn.bootstrapTable.theme] || 'fa-trash'
  532. })
  533. $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales)
  534. $.extend($.fn.bootstrapTable.defaults, {
  535. formatClearSearch () {
  536. return 'Clear filters'
  537. }
  538. })
  539. $.fn.bootstrapTable.methods.push('triggerSearch')
  540. $.fn.bootstrapTable.methods.push('clearFilterControl')
  541. $.BootstrapTable = class extends $.BootstrapTable {
  542. init () {
  543. UtilsFilterControl.bootstrapTableInstance = this
  544. // Make sure that the filterControl option is set
  545. if (this.options.filterControl) {
  546. const that = this
  547. // Make sure that the internal variables are set correctly
  548. this.options.valuesFilterControl = []
  549. this.$el
  550. .on('reset-view.bs.table', () => {
  551. // Create controls on $tableHeader if the height is set
  552. if (!that.options.height) {
  553. return
  554. }
  555. // Avoid recreate the controls
  556. if (
  557. UtilsFilterControl.getControlContainer().find('select').length > 0 ||
  558. UtilsFilterControl.getControlContainer().find('input').length > 0
  559. ) {
  560. return
  561. }
  562. UtilsFilterControl.createControls(that, UtilsFilterControl.getControlContainer())
  563. })
  564. .on('post-header.bs.table', () => {
  565. UtilsFilterControl.setValues(that)
  566. })
  567. .on('post-body.bs.table', () => {
  568. if (that.options.height && !that.options.filterControlContainer) {
  569. UtilsFilterControl.fixHeaderCSS(that)
  570. }
  571. this.$tableLoading.css('top', this.$header.outerHeight() + 1)
  572. })
  573. .on('column-switch.bs.table', () => {
  574. UtilsFilterControl.setValues(that)
  575. })
  576. .on('load-success.bs.table', () => {
  577. that.enableControls(true)
  578. })
  579. .on('load-error.bs.table', () => {
  580. that.enableControls(true)
  581. })
  582. }
  583. super.init()
  584. }
  585. initHeader () {
  586. super.initHeader()
  587. if (!this.options.filterControl) {
  588. return
  589. }
  590. UtilsFilterControl.createControls(this, UtilsFilterControl.getControlContainer())
  591. }
  592. initBody () {
  593. super.initBody()
  594. UtilsFilterControl.initFilterSelectControls(this)
  595. }
  596. initSearch () {
  597. const that = this
  598. const fp = $.isEmptyObject(that.filterColumnsPartial)
  599. ? null
  600. : that.filterColumnsPartial
  601. if (fp === null || Object.keys(fp).length <= 1) {
  602. super.initSearch()
  603. }
  604. if (this.options.sidePagination === 'server') {
  605. return
  606. }
  607. if (fp === null) {
  608. return
  609. }
  610. // Check partial column filter
  611. that.data = fp
  612. ? that.options.data.filter((item, i) => {
  613. const itemIsExpected = []
  614. Object.keys(item).forEach((x, index) => {
  615. const key = that.header.fields[index]
  616. const thisColumn = that.columns[that.fieldsColumnsIndex[key]]
  617. const fval = (fp[key] || '').toLowerCase()
  618. let value = Utils.getItemField(item, key, false)
  619. if (fval === '') {
  620. itemIsExpected.push(true)
  621. } else {
  622. // Fix #142: search use formatted data
  623. if (thisColumn && thisColumn.searchFormatter) {
  624. value = $.fn.bootstrapTable.utils.calculateObjectValue(
  625. that.header,
  626. that.header.formatters[$.inArray(key, that.header.fields)],
  627. [value, item, i],
  628. value
  629. )
  630. }
  631. if ($.inArray(key, that.header.fields) !== -1) {
  632. if (value === undefined || value === null) {
  633. itemIsExpected.push(false)
  634. } else if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
  635. if (thisColumn.filterStrictSearch) {
  636. itemIsExpected.push(value.toString().toLowerCase() === fval.toString().toLowerCase())
  637. } else if (thisColumn.filterStartsWithSearch) {
  638. itemIsExpected.push((`${value}`).toLowerCase().indexOf(fval) === 0)
  639. } else {
  640. itemIsExpected.push((`${value}`).toLowerCase().includes(fval))
  641. }
  642. }
  643. }
  644. }
  645. })
  646. return !itemIsExpected.includes(false)
  647. })
  648. : that.data
  649. }
  650. initColumnSearch (filterColumnsDefaults) {
  651. UtilsFilterControl.copyValues(this)
  652. if (filterColumnsDefaults) {
  653. this.filterColumnsPartial = filterColumnsDefaults
  654. this.updatePagination()
  655. // eslint-disable-next-line guard-for-in
  656. for (const filter in filterColumnsDefaults) {
  657. this.trigger('column-search', filter, filterColumnsDefaults[filter])
  658. }
  659. }
  660. }
  661. onColumnSearch ({currentTarget, keyCode}) {
  662. if ($.inArray(keyCode, [37, 38, 39, 40]) > -1) {
  663. return
  664. }
  665. UtilsFilterControl.copyValues(this)
  666. const text = $.trim($(currentTarget).val())
  667. const $field = $(currentTarget)
  668. .closest('[data-field]')
  669. .data('field')
  670. if ($.isEmptyObject(this.filterColumnsPartial)) {
  671. this.filterColumnsPartial = {}
  672. }
  673. if (text) {
  674. this.filterColumnsPartial[$field] = text
  675. } else {
  676. delete this.filterColumnsPartial[$field]
  677. }
  678. this.options.pageNumber = 1
  679. this.enableControls(false)
  680. this.onSearch({currentTarget}, false)
  681. this.trigger('column-search', $field, text)
  682. }
  683. initToolbar () {
  684. this.showSearchClearButton = this.options.filterControl && this.options.showSearchClearButton
  685. super.initToolbar()
  686. }
  687. resetSearch () {
  688. if (this.options.filterControl && this.options.showSearchClearButton) {
  689. this.clearFilterControl()
  690. }
  691. super.resetSearch()
  692. }
  693. clearFilterControl () {
  694. if (this.options.filterControl) {
  695. const that = this
  696. const cookies = UtilsFilterControl.collectBootstrapCookies()
  697. const header = UtilsFilterControl.getCurrentHeader(that)
  698. const table = header.closest('table')
  699. const controls = header.find(UtilsFilterControl.getCurrentSearchControls(that))
  700. const search = that.$toolbar.find('.search input')
  701. let hasValues = false
  702. let timeoutId = 0
  703. $.each(that.options.valuesFilterControl, (i, item) => {
  704. hasValues = hasValues ? true : item.value !== ''
  705. item.value = ''
  706. })
  707. $.each(that.options.filterControls, (i, item) => {
  708. item.text = ''
  709. })
  710. UtilsFilterControl.setValues(that)
  711. // clear cookies once the filters are clean
  712. clearTimeout(timeoutId)
  713. timeoutId = setTimeout(() => {
  714. if (cookies && cookies.length > 0) {
  715. $.each(cookies, (i, item) => {
  716. if (that.deleteCookie !== undefined) {
  717. that.deleteCookie(item)
  718. }
  719. })
  720. }
  721. }, that.options.searchTimeOut)
  722. // If there is not any value in the controls exit this method
  723. if (!hasValues) {
  724. return
  725. }
  726. // Clear each type of filter if it exists.
  727. // Requires the body to reload each time a type of filter is found because we never know
  728. // which ones are going to be present.
  729. if (controls.length > 0) {
  730. this.filterColumnsPartial = {}
  731. $(controls[0]).trigger(
  732. controls[0].tagName === 'INPUT' ? 'keyup' : 'change', {keyCode: 13}
  733. )
  734. } else {
  735. return
  736. }
  737. if (search.length > 0) {
  738. that.resetSearch()
  739. }
  740. // use the default sort order if it exists. do nothing if it does not
  741. if (
  742. that.options.sortName !== table.data('sortName') ||
  743. that.options.sortOrder !== table.data('sortOrder')
  744. ) {
  745. const sorter = header.find(
  746. Utils.sprintf(
  747. '[data-field="%s"]',
  748. $(controls[0])
  749. .closest('table')
  750. .data('sortName')
  751. )
  752. )
  753. if (sorter.length > 0) {
  754. that.onSort({type: 'keypress', currentTarget: sorter})
  755. $(sorter)
  756. .find('.sortable')
  757. .trigger('click')
  758. }
  759. }
  760. }
  761. }
  762. triggerSearch () {
  763. const searchControls = UtilsFilterControl.getSearchControls(this)
  764. searchControls.each(function () {
  765. const el = $(this)
  766. if (el.is('select')) {
  767. el.change()
  768. } else {
  769. el.keyup()
  770. }
  771. })
  772. }
  773. enableControls (enable) {
  774. if (
  775. this.options.disableControlWhenSearch &&
  776. this.options.sidePagination === 'server'
  777. ) {
  778. const searchControls = UtilsFilterControl.getSearchControls(this)
  779. if (!enable) {
  780. searchControls.prop('disabled', 'disabled')
  781. } else {
  782. searchControls.removeProp('disabled')
  783. }
  784. }
  785. }
  786. }