bootstrap-table-filter-control.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  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. uniqueValues[formattedValue] = fieldValue
  221. if (typeof formattedValue === 'object' && formattedValue !== null) {
  222. formattedValue.forEach((value) => {
  223. UtilsFilterControl.addOptionToSelectControl(selectControl, value, value, column.filterDefault)
  224. })
  225. continue
  226. }
  227. UtilsFilterControl.addOptionToSelectControl(selectControl, formattedValue, formattedValue, column.filterDefault)
  228. }
  229. UtilsFilterControl.sortSelectControl(selectControl, column.filterOrderBy)
  230. if (that.options.hideUnusedSelectOptions) {
  231. UtilsFilterControl.hideUnusedSelectOptions(selectControl, uniqueValues)
  232. }
  233. }
  234. })
  235. that.trigger('created-controls')
  236. },
  237. getFilterDataMethod (objFilterDataMethod, searchTerm) {
  238. const keys = Object.keys(objFilterDataMethod)
  239. for (let i = 0; i < keys.length; i++) {
  240. if (keys[i] === searchTerm) {
  241. return objFilterDataMethod[searchTerm]
  242. }
  243. }
  244. return null
  245. },
  246. createControls (that, header) {
  247. let addedFilterControl = false
  248. let isVisible
  249. let html
  250. $.each(that.columns, (i, column) => {
  251. html = []
  252. if (!column.visible) {
  253. return
  254. }
  255. if (!column.filterControl && !that.options.filterControlContainer) {
  256. html.push('<div class="no-filter-control"></div>')
  257. } else if (that.options.filterControlContainer) {
  258. const $filterControl = $(`.bootstrap-table-filter-control-${column.field}`)
  259. const placeholder = column.filterControlPlaceholder ? column.filterControlPlaceholder : ''
  260. $filterControl.attr('placeholder', placeholder)
  261. $filterControl.val(column.filterDefault)
  262. $filterControl.attr('data-field', column.field)
  263. addedFilterControl = true
  264. } else {
  265. const nameControl = column.filterControl.toLowerCase()
  266. html.push('<div class="filter-control">')
  267. addedFilterControl = true
  268. if (column.searchable && that.options.filterTemplate[nameControl]) {
  269. html.push(
  270. that.options.filterTemplate[nameControl](
  271. that,
  272. column.field,
  273. column.filterControlPlaceholder
  274. ? column.filterControlPlaceholder
  275. : '',
  276. column.filterDefault
  277. )
  278. )
  279. }
  280. }
  281. if (!column.filterControl && '' !== column.filterDefault && 'undefined' !== typeof column.filterDefault) {
  282. if ($.isEmptyObject(that.filterColumnsPartial)) {
  283. that.filterColumnsPartial = {}
  284. }
  285. that.filterColumnsPartial[column.field] = column.filterDefault
  286. }
  287. $.each(header.children().children(), (i, tr) => {
  288. const $tr = $(tr)
  289. if ($tr.data('field') === column.field) {
  290. $tr.find('.fht-cell').append(html.join(''))
  291. return false
  292. }
  293. })
  294. if (
  295. column.filterData !== undefined &&
  296. column.filterData.toLowerCase() !== 'column'
  297. ) {
  298. const filterDataType = UtilsFilterControl.getFilterDataMethod(
  299. /* eslint-disable no-use-before-define */
  300. filterDataMethods,
  301. column.filterData.substring(0, column.filterData.indexOf(':'))
  302. )
  303. let filterDataSource
  304. let selectControl
  305. if (filterDataType !== null) {
  306. filterDataSource = column.filterData.substring(
  307. column.filterData.indexOf(':') + 1,
  308. column.filterData.length
  309. )
  310. selectControl = UtilsFilterControl.getControlContainer().find(`.bootstrap-table-filter-control-${UtilsFilterControl.escapeID(column.field)}`)
  311. UtilsFilterControl.addOptionToSelectControl(selectControl, '', column.filterControlPlaceholder, column.filterDefault)
  312. filterDataType(filterDataSource, selectControl, column.filterDefault)
  313. } else {
  314. throw new SyntaxError(
  315. 'Error. You should use any of these allowed filter data methods: var, json, url.' +
  316. ' Use like this: var: {key: "value"}'
  317. )
  318. }
  319. let variableValues
  320. let key
  321. // eslint-disable-next-line default-case
  322. switch (filterDataType) {
  323. case 'url':
  324. $.ajax({
  325. url: filterDataSource,
  326. dataType: 'json',
  327. success (data) {
  328. // eslint-disable-next-line guard-for-in
  329. for (const key in data) {
  330. UtilsFilterControl.addOptionToSelectControl(selectControl, key, data[key], column.filterDefault)
  331. }
  332. UtilsFilterControl.sortSelectControl(selectControl, column.filterOrderBy)
  333. }
  334. })
  335. break
  336. case 'var':
  337. variableValues = window[filterDataSource]
  338. // eslint-disable-next-line guard-for-in
  339. for (key in variableValues) {
  340. UtilsFilterControl.addOptionToSelectControl(selectControl, key, variableValues[key], column.filterDefault)
  341. }
  342. UtilsFilterControl.sortSelectControl(selectControl, column.filterOrderBy)
  343. break
  344. case 'jso':
  345. variableValues = JSON.parse(filterDataSource)
  346. // eslint-disable-next-line guard-for-in
  347. for (key in variableValues) {
  348. UtilsFilterControl.addOptionToSelectControl(selectControl, key, variableValues[key], column.filterDefault)
  349. }
  350. UtilsFilterControl.sortSelectControl(selectControl, column.filterOrderBy)
  351. break
  352. }
  353. }
  354. })
  355. if (addedFilterControl) {
  356. UtilsFilterControl.getControlContainer().off('keyup', 'input').on('keyup', 'input', ({currentTarget, keyCode}, obj) => {
  357. // Simulate enter key action from clear button
  358. keyCode = obj ? obj.keyCode : keyCode
  359. if (that.options.searchOnEnterKey && keyCode !== 13) {
  360. return
  361. }
  362. if ($.inArray(keyCode, [37, 38, 39, 40]) > -1) {
  363. return
  364. }
  365. const $currentTarget = $(currentTarget)
  366. if ($currentTarget.is(':checkbox') || $currentTarget.is(':radio')) {
  367. return
  368. }
  369. clearTimeout(currentTarget.timeoutId || 0)
  370. currentTarget.timeoutId = setTimeout(() => {
  371. that.onColumnSearch({currentTarget, keyCode})
  372. }, that.options.searchTimeOut)
  373. })
  374. UtilsFilterControl.getControlContainer().off('change', 'select').on('change', 'select', ({currentTarget, keyCode}) => {
  375. if (that.options.searchOnEnterKey && keyCode !== 13) {
  376. return
  377. }
  378. if ($.inArray(keyCode, [37, 38, 39, 40]) > -1) {
  379. return
  380. }
  381. clearTimeout(currentTarget.timeoutId || 0)
  382. currentTarget.timeoutId = setTimeout(() => {
  383. that.onColumnSearch({currentTarget, keyCode})
  384. }, that.options.searchTimeOut)
  385. })
  386. header.off('mouseup', 'input').on('mouseup', 'input', ({currentTarget, keyCode}) => {
  387. const $input = $(currentTarget)
  388. const oldValue = $input.val()
  389. if (oldValue === '') {
  390. return
  391. }
  392. setTimeout(() => {
  393. const newValue = $input.val()
  394. if (newValue === '') {
  395. clearTimeout(currentTarget.timeoutId || 0)
  396. currentTarget.timeoutId = setTimeout(() => {
  397. that.onColumnSearch({currentTarget, keyCode})
  398. }, that.options.searchTimeOut)
  399. }
  400. }, 1)
  401. })
  402. if (UtilsFilterControl.getControlContainer().find('.date-filter-control').length > 0) {
  403. $.each(that.columns, (i, {filterControl, field, filterDatepickerOptions}) => {
  404. if (
  405. filterControl !== undefined &&
  406. filterControl.toLowerCase() === 'datepicker'
  407. ) {
  408. UtilsFilterControl.getControlContainer()
  409. .find(
  410. `.date-filter-control.bootstrap-table-filter-control-${field}`
  411. )
  412. .datepicker(filterDatepickerOptions)
  413. .on('changeDate', ({currentTarget, keyCode}) => {
  414. clearTimeout(currentTarget.timeoutId || 0)
  415. currentTarget.timeoutId = setTimeout(() => {
  416. that.onColumnSearch({currentTarget, keyCode})
  417. }, that.options.searchTimeOut)
  418. })
  419. }
  420. })
  421. }
  422. if (that.options.sidePagination !== 'server') {
  423. that.triggerSearch()
  424. }
  425. } else {
  426. UtilsFilterControl.getControlContainer().find('.filterControl').hide()
  427. }
  428. },
  429. getDirectionOfSelectOptions (_alignment) {
  430. const alignment = _alignment === undefined ? 'left' : _alignment.toLowerCase()
  431. switch (alignment) {
  432. case 'left':
  433. return 'ltr'
  434. case 'right':
  435. return 'rtl'
  436. case 'auto':
  437. return 'auto'
  438. default:
  439. return 'ltr'
  440. }
  441. }
  442. }
  443. const filterDataMethods = {
  444. var (filterDataSource, selectControl, filterOrderBy, selected) {
  445. const variableValues = window[filterDataSource]
  446. // eslint-disable-next-line guard-for-in
  447. for (const key in variableValues) {
  448. UtilsFilterControl.addOptionToSelectControl(selectControl, key, variableValues[key], selected)
  449. }
  450. UtilsFilterControl.sortSelectControl(selectControl, filterOrderBy)
  451. },
  452. url (filterDataSource, selectControl, filterOrderBy, selected) {
  453. $.ajax({
  454. url: filterDataSource,
  455. dataType: 'json',
  456. success (data) {
  457. // eslint-disable-next-line guard-for-in
  458. for (const key in data) {
  459. UtilsFilterControl.addOptionToSelectControl(selectControl, key, data[key], selected)
  460. }
  461. UtilsFilterControl.sortSelectControl(selectControl, filterOrderBy)
  462. }
  463. })
  464. },
  465. json (filterDataSource, selectControl, filterOrderBy, selected) {
  466. const variableValues = JSON.parse(filterDataSource)
  467. // eslint-disable-next-line guard-for-in
  468. for (const key in variableValues) {
  469. UtilsFilterControl.addOptionToSelectControl(selectControl, key, variableValues[key], selected)
  470. }
  471. UtilsFilterControl.sortSelectControl(selectControl, filterOrderBy)
  472. }
  473. }
  474. $.extend($.fn.bootstrapTable.defaults, {
  475. filterControl: false,
  476. onColumnSearch (field, text) {
  477. return false
  478. },
  479. onCreatedControls () {
  480. return true
  481. },
  482. alignmentSelectControlOptions: undefined,
  483. filterTemplate: {
  484. input (that, field, placeholder, value) {
  485. return Utils.sprintf(
  486. '<input type="text" class="form-control bootstrap-table-filter-control-%s" style="width: 100%;" placeholder="%s" value="%s">',
  487. field,
  488. 'undefined' === typeof placeholder ? '' : placeholder,
  489. 'undefined' === typeof value ? '' : value
  490. )
  491. },
  492. select ({options}, field) {
  493. return Utils.sprintf(
  494. '<select class="form-control bootstrap-table-filter-control-%s" style="width: 100%;" dir="%s"></select>',
  495. field,
  496. UtilsFilterControl.getDirectionOfSelectOptions(
  497. options.alignmentSelectControlOptions
  498. )
  499. )
  500. },
  501. datepicker (that, field, value) {
  502. return Utils.sprintf(
  503. '<input type="text" class="form-control date-filter-control bootstrap-table-filter-control-%s" style="width: 100%;" value="%s">',
  504. field,
  505. 'undefined' === typeof value ? '' : value
  506. )
  507. }
  508. },
  509. disableControlWhenSearch: false,
  510. searchOnEnterKey: false,
  511. // internal variables
  512. valuesFilterControl: []
  513. })
  514. $.extend($.fn.bootstrapTable.columnDefaults, {
  515. filterControl: undefined,
  516. filterDataCollector: undefined,
  517. filterData: undefined,
  518. filterDatepickerOptions: undefined,
  519. filterStrictSearch: false,
  520. filterStartsWithSearch: false,
  521. filterControlPlaceholder: '',
  522. filterDefault: '',
  523. filterOrderBy: 'asc' // asc || desc
  524. })
  525. $.extend($.fn.bootstrapTable.Constructor.EVENTS, {
  526. 'column-search.bs.table': 'onColumnSearch',
  527. 'created-controls.bs.table': 'onCreatedControls'
  528. })
  529. $.extend($.fn.bootstrapTable.defaults.icons, {
  530. clear: {
  531. bootstrap3: 'glyphicon-trash icon-clear'
  532. }[$.fn.bootstrapTable.theme] || 'fa-trash'
  533. })
  534. $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales)
  535. $.extend($.fn.bootstrapTable.defaults, {
  536. formatClearSearch () {
  537. return 'Clear filters'
  538. }
  539. })
  540. $.fn.bootstrapTable.methods.push('triggerSearch')
  541. $.fn.bootstrapTable.methods.push('clearFilterControl')
  542. $.BootstrapTable = class extends $.BootstrapTable {
  543. init () {
  544. UtilsFilterControl.bootstrapTableInstance = this
  545. // Make sure that the filterControl option is set
  546. if (this.options.filterControl) {
  547. const that = this
  548. // Make sure that the internal variables are set correctly
  549. this.options.valuesFilterControl = []
  550. this.$el
  551. .on('reset-view.bs.table', () => {
  552. // Create controls on $tableHeader if the height is set
  553. if (!that.options.height) {
  554. return
  555. }
  556. // Avoid recreate the controls
  557. if (
  558. UtilsFilterControl.getControlContainer().find('select').length > 0 ||
  559. UtilsFilterControl.getControlContainer().find('input').length > 0
  560. ) {
  561. return
  562. }
  563. UtilsFilterControl.createControls(that, UtilsFilterControl.getControlContainer())
  564. })
  565. .on('post-header.bs.table', () => {
  566. UtilsFilterControl.setValues(that)
  567. })
  568. .on('post-body.bs.table', () => {
  569. if (that.options.height && !that.options.filterControlContainer) {
  570. UtilsFilterControl.fixHeaderCSS(that)
  571. }
  572. this.$tableLoading.css('top', this.$header.outerHeight() + 1)
  573. })
  574. .on('column-switch.bs.table', () => {
  575. UtilsFilterControl.setValues(that)
  576. })
  577. .on('load-success.bs.table', () => {
  578. that.enableControls(true)
  579. })
  580. .on('load-error.bs.table', () => {
  581. that.enableControls(true)
  582. })
  583. }
  584. super.init()
  585. }
  586. initHeader () {
  587. super.initHeader()
  588. if (!this.options.filterControl) {
  589. return
  590. }
  591. UtilsFilterControl.createControls(this, UtilsFilterControl.getControlContainer())
  592. }
  593. initBody () {
  594. super.initBody()
  595. UtilsFilterControl.initFilterSelectControls(this)
  596. }
  597. initSearch () {
  598. const that = this
  599. const fp = $.isEmptyObject(that.filterColumnsPartial)
  600. ? null
  601. : that.filterColumnsPartial
  602. if (fp === null || Object.keys(fp).length <= 1) {
  603. super.initSearch()
  604. }
  605. if (this.options.sidePagination === 'server') {
  606. return
  607. }
  608. if (fp === null) {
  609. return
  610. }
  611. // Check partial column filter
  612. that.data = fp
  613. ? that.options.data.filter((item, i) => {
  614. const itemIsExpected = []
  615. const keys1 = Object.keys(item)
  616. const keys2 = Object.keys(fp)
  617. const keys = keys1.concat(keys2.filter(item => !keys1.includes(item)))
  618. keys.forEach(key => {
  619. const thisColumn = that.columns[that.fieldsColumnsIndex[key]]
  620. const fval = (fp[key] || '').toLowerCase()
  621. let value = Utils.getItemField(item, key, false)
  622. if (fval === '') {
  623. itemIsExpected.push(true)
  624. } else {
  625. // Fix #142: search use formatted data
  626. if (thisColumn && thisColumn.searchFormatter) {
  627. value = $.fn.bootstrapTable.utils.calculateObjectValue(
  628. that.header,
  629. that.header.formatters[$.inArray(key, that.header.fields)],
  630. [value, item, i],
  631. value
  632. )
  633. }
  634. if ($.inArray(key, that.header.fields) !== -1) {
  635. if (value === undefined || value === null) {
  636. itemIsExpected.push(false)
  637. } else if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
  638. if (thisColumn.filterStrictSearch) {
  639. itemIsExpected.push(value.toString().toLowerCase() === fval.toString().toLowerCase())
  640. } else if (thisColumn.filterStartsWithSearch) {
  641. itemIsExpected.push((`${value}`).toLowerCase().indexOf(fval) === 0)
  642. } else {
  643. itemIsExpected.push((`${value}`).toLowerCase().includes(fval))
  644. }
  645. }
  646. }
  647. }
  648. })
  649. return !itemIsExpected.includes(false)
  650. })
  651. : that.data
  652. }
  653. initColumnSearch (filterColumnsDefaults) {
  654. UtilsFilterControl.copyValues(this)
  655. if (filterColumnsDefaults) {
  656. this.filterColumnsPartial = filterColumnsDefaults
  657. this.updatePagination()
  658. // eslint-disable-next-line guard-for-in
  659. for (const filter in filterColumnsDefaults) {
  660. this.trigger('column-search', filter, filterColumnsDefaults[filter])
  661. }
  662. }
  663. }
  664. onColumnSearch ({currentTarget, keyCode}) {
  665. if ($.inArray(keyCode, [37, 38, 39, 40]) > -1) {
  666. return
  667. }
  668. UtilsFilterControl.copyValues(this)
  669. const text = $.trim($(currentTarget).val())
  670. const $field = $(currentTarget)
  671. .closest('[data-field]')
  672. .data('field')
  673. if ($.isEmptyObject(this.filterColumnsPartial)) {
  674. this.filterColumnsPartial = {}
  675. }
  676. if (text) {
  677. this.filterColumnsPartial[$field] = text
  678. } else {
  679. delete this.filterColumnsPartial[$field]
  680. }
  681. this.options.pageNumber = 1
  682. this.enableControls(false)
  683. this.onSearch({currentTarget}, false)
  684. this.trigger('column-search', $field, text)
  685. }
  686. initToolbar () {
  687. this.showSearchClearButton = this.options.filterControl && this.options.showSearchClearButton
  688. super.initToolbar()
  689. }
  690. resetSearch () {
  691. if (this.options.filterControl && this.options.showSearchClearButton) {
  692. this.clearFilterControl()
  693. }
  694. super.resetSearch()
  695. }
  696. clearFilterControl () {
  697. if (this.options.filterControl) {
  698. const that = this
  699. const cookies = UtilsFilterControl.collectBootstrapCookies()
  700. const header = UtilsFilterControl.getCurrentHeader(that)
  701. const table = header.closest('table')
  702. const controls = header.find(UtilsFilterControl.getCurrentSearchControls(that))
  703. const search = that.$toolbar.find('.search input')
  704. let hasValues = false
  705. let timeoutId = 0
  706. $.each(that.options.valuesFilterControl, (i, item) => {
  707. hasValues = hasValues ? true : item.value !== ''
  708. item.value = ''
  709. })
  710. $.each(that.options.filterControls, (i, item) => {
  711. item.text = ''
  712. })
  713. UtilsFilterControl.setValues(that)
  714. // clear cookies once the filters are clean
  715. clearTimeout(timeoutId)
  716. timeoutId = setTimeout(() => {
  717. if (cookies && cookies.length > 0) {
  718. $.each(cookies, (i, item) => {
  719. if (that.deleteCookie !== undefined) {
  720. that.deleteCookie(item)
  721. }
  722. })
  723. }
  724. }, that.options.searchTimeOut)
  725. // If there is not any value in the controls exit this method
  726. if (!hasValues) {
  727. return
  728. }
  729. // Clear each type of filter if it exists.
  730. // Requires the body to reload each time a type of filter is found because we never know
  731. // which ones are going to be present.
  732. if (controls.length > 0) {
  733. this.filterColumnsPartial = {}
  734. $(controls[0]).trigger(
  735. controls[0].tagName === 'INPUT' ? 'keyup' : 'change', {keyCode: 13}
  736. )
  737. } else {
  738. return
  739. }
  740. if (search.length > 0) {
  741. that.resetSearch()
  742. }
  743. // use the default sort order if it exists. do nothing if it does not
  744. if (
  745. that.options.sortName !== table.data('sortName') ||
  746. that.options.sortOrder !== table.data('sortOrder')
  747. ) {
  748. const sorter = header.find(
  749. Utils.sprintf(
  750. '[data-field="%s"]',
  751. $(controls[0])
  752. .closest('table')
  753. .data('sortName')
  754. )
  755. )
  756. if (sorter.length > 0) {
  757. that.onSort({type: 'keypress', currentTarget: sorter})
  758. $(sorter)
  759. .find('.sortable')
  760. .trigger('click')
  761. }
  762. }
  763. }
  764. }
  765. triggerSearch () {
  766. const searchControls = UtilsFilterControl.getSearchControls(this)
  767. searchControls.each(function () {
  768. const el = $(this)
  769. if (el.is('select')) {
  770. el.change()
  771. } else {
  772. el.keyup()
  773. }
  774. })
  775. }
  776. enableControls (enable) {
  777. if (
  778. this.options.disableControlWhenSearch &&
  779. this.options.sidePagination === 'server'
  780. ) {
  781. const searchControls = UtilsFilterControl.getSearchControls(this)
  782. if (!enable) {
  783. searchControls.prop('disabled', 'disabled')
  784. } else {
  785. searchControls.removeProp('disabled')
  786. }
  787. }
  788. }
  789. }