Перейти к содержимому

Filter rule builder js что это такое

  • автор:

How to implement JQuery Query Builder rule filter autocomplete

After spending lot of time with JQuery query builder extensions to make rule filter as autocomplete functionalities.

$('#build-query').queryBuilder( < plugins: ['sortable', 'bt-tooltip-errors', 'bt-checkbox', 'invert', 'not-group', 'filter-description'], allow_empty: true, filters: result, rules: customFilters, icons: < add_group: 'fa fa-plus-square', add_rule: 'fa fa-plus-circle', remove_group: 'fa fa-minus-square', remove_rule: 'fa fa-minus-circle', error: 'fa fa-exclamation-triangle', sortable: 'fa fa-exclamation-triangle' >>).on('afterCreateRuleFilters.queryBuilder', function (e, rule) < rule.$el.find(QueryBuilder.selectors.rule_filter).selectpicker(< liveSearch: true, style:'width: 500px;', >); >); 

Please make sure you add supporting javascript references like Jquery builder standlone.js, css Bootstrap.js , css bootstrap selectpicker js , css

enter image description here

answered Aug 18, 2021 at 17:04
Muni Chittem Muni Chittem
1,008 10 10 silver badges 17 17 bronze badges

You need to configure a plugin, and use the selectize plugin

const namesList = [< id: '1', name: 'andrew' >, < id: '2', name: 'bob' >, < id: '3', name: 'charles' >, < id: '4', name: 'david' >, < id: '5', name: 'emily' >, < id: '6', name: 'frank' >, < id: '7', name: 'george' >, < id: '8', name: 'harry' >, < id: '9', name: 'isabelle' >, < id: '10', name: 'jerry' >]; let pluginConfig = < preload: true, valueField: 'id', labelField: 'name', searchField: 'name', options: namesList, items: ['2'], allowEmptyOption: true, plugins: ['remove_button'], onInitialize: function () < >, onChange: function (value) < >, valueSetter: function (rule, value) < rule.$el.find('.rule-value-container input')[0].selectize.setValue(value); >, valueGetter: function (rule) < var val = rule.$el.find('.rule-value-container input')[0].selectize.getValue(); return val.split(','); >> let filterList = [< id: 'age', type: 'integer', input: 'text' >, < id: 'name', label: 'name', name: 'name', type: 'string', input: 'text', plugin: 'selectize', plugin_config: pluginConfig >]; let options = < allow_empty: true, operators: ['equal', 'not_equal', 'greater', 'greater_or_equal', 'less', 'less_or_equal'], filters: filterList >$('#builder').queryBuilder(options); // Fix for Selectize $('#builder').on('afterCreateRuleInput.queryBuilder', function (e, rule) < if (rule.filter.plugin == 'selectize') < rule.$el.find('.rule-value-container').css('min-width', '200px') .find('.selectize-control').removeClass('form-control'); >>); // Capture the change event $('#builder').on('afterCreateRuleInput.queryBuilder', function (e, rule) < var filter = rule.filter; var input = rule.$el.find('.rule-value-container input'); if (filter.id === 'name') < input.on('change', function () < console.log('name value changed to: ' + input.val()); let filtersJSON = $('#builder').queryBuilder('getRules', < allow_invalid: true >); console.log(JSON.stringify(filtersJSON, null, 2)); >); > >); 

Webix UI 4.4 Release Overview

JavaScript UI framework with Print API

The new release 4.4 of Webix JavaScript UI library is available for download. Let’s have a look at the changes and new functionality: Print API, Query Builder, Demos of Integration with PHP, Node.js and .NET.

Printing from Applications

  • the print area
  • the paper size
  • the margins
  • page orientation and scale
  • headers, grid lines and empty rows printing

The variety of printing options depends on the type of a widget. The complex widget Spreadsheet features a built-in printing functionality:

Advanced Filtering

Query Builder, the 89th Webix widget, is a constructor of complex rules for filtering. You can use it with any data components of the library. From now on, the DataTable widget allows using the Query Builder as a built-in filter.

The new widget allows building complex filters by grouping several rules (or even groups of rules) based on the specified conditions (AND or OR). Each rule includes a criterion that the filtered values should meet. Query Builder widget is available only for Webix PRO.

Clear Integration with Backend Platforms

The new demos, that can be found on GitHub, are aimed at simplifying integration with:

The demos show how to connect Webix UI with these backend platforms. We are planning to expand the list of demos on integration with backend platforms.

The Site Update

You must have noticed that the Webix site looks different. We are doing our best to keep up with the times and gradually adding new parts to the site. We have added a page with video tutorials, simplified the form on the Trial download page of Webix PRO with all complex widgets, upgraded the license page. From now on you can add the necessary number of licenses for complex widgets to your Team Pack.

Minor Changes

Disabled menu items

We added the special attribute for the Menu widget. This attribute allows disabling certain menu items during the initialization of the component.

Updated integration with Google Maps

Integration with Google Maps was improved and included into the library as a separate widget. Since version 4.4 we have removed the outdated integration from the components repository on GitHub and from CDN.

You can find the complete list of changes on the What’s new page.

Try the Trial version of Webix PRO with complex widgets Pivot, Kanban, Scheduler, Spreadsheet, File Manager and feel free to give your feedback. Clients with an active license can download the new release from the Client Area or via CDN.

Meanwhile we are working on release 5.0. It will include awesome updates and long-expected features ��

Written by

  • Bio
  • Latest Posts

Array.prototype.filter()

Метод filter() создаёт новый массив со всеми элементами, прошедшими проверку, задаваемую в передаваемой функции.

Интерактивный пример

Синтаксис

// Стрелочная функция filter((element) =>  . > ) filter((element, index) =>  . > ) filter((element, index, array) =>  . > ) // Колбэк-функция filter(callbackFn) filter(callbackFn, thisArg) // Встроенная колбэк-функция filter(function callbackFn(element)  . >) filter(function callbackFn(element, index)  . >) filter(function callbackFn(element, index, array) . >) filter(function callbackFn(element, index, array)  . >, thisArg) 

Параметры

Функция-предикат, которая будет вызвана для проверки каждого элемента массива. Если функция возвращает true , то элемент остаётся в массиве, если false , то удаляется.

Принимает три аргумента

Текущий обрабатываемый элемент в массиве.

Индекс текущего обрабатываемого элемента в массиве.

Обрабатываемый массив, на котором был вызван метод filter() .

Значение, используемое в качестве this при вызове колбэк-функции callbackFn .

Возвращаемое значение

Вернётся новый массив с элементами, которые прошли проверку. Если ни один элемент не прошёл проверку, то будет возвращён пустой массив.

Описание

Метод filter() вызывает переданную функцию callback один раз для каждого элемента, присутствующего в массиве, и создаёт новый массив со всеми значениями, для которых функция callback вернула значение, которое может быть приведено к true . Функция callback вызывается только для индексов массива с уже определёнными значениями; она не вызывается для индексов, которые были удалены или которым значения никогда не присваивались. Элементы массива, не прошедшие проверку функцией callback , просто пропускаются и не включаются в новый массив.

Функция callback вызывается с тремя аргументами:

  1. значение элемента;
  2. индекс элемента;
  3. массив, по которому осуществляется проход.

Если в метод filter() был передан параметр thisArg , при вызове callback он будет использоваться в качестве значения this . В противном случае в качестве значения this будет использоваться значение undefined . В конечном итоге, значение this , наблюдаемое из функции callback , определяется согласно обычным правилам определения this .

Метод filter() не изменяет массив, для которого он был вызван.

Элементы массива, обрабатываемые методом filter() , устанавливается до первого вызова функции callback . Элементы, добавленные в массив после начала выполнения метода filter() , либо изменённые в процессе выполнения, не будут обработаны функцией callback . Соответствующим образом, если существующие элементы удаляются из массива, они также не будут обработаны

Предупреждение: одновременное изменение элементов, описанное в предыдущем параграфе, часто приводит к труднопонимаемому коду, поэтому не рекомендуется делать это (за исключением особых случаев).

Примеры

Фильтрация всех маленьких значений

Следующий пример использует filter() для создания отфильтрованного массива, все элементы которого больше или равны 10, а все меньшие 10 удалены.

function isBigEnough(value)  return value >= 10; > let filtered = [12, 5, 8, 130, 44].filter(isBigEnough); // массив filtered теперь содержит [12, 130, 44] 

Найти все простые числа в массиве

Следующий пример возвращает все простые числа в массиве:

const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]; function isPrime(num)  for (let i = 2; num > i; i++)  if (num % i == 0)  return false; > > return num > 1; > console.log(array.filter(isPrime)); // [2, 3, 5, 7, 11, 13] 

Фильтрация неверных записей в JSON

В следующем примере метод filter() используется для создания отфильтрованного JSON-объекта, все элементы которого содержат ненулевое числовое поле id .

let arr = [  id: 15 >,  id: -1 >,  id: 0 >,  id: 3 >,  id: 12.2 >, >,  id: null >,  id: NaN >,  id: "undefined" >, ]; let invalidEntries = 0; function filterByID(item)  if (Number.isFinite(item.id) && item.id !== 0)  return true; > invalidEntries++; return false; > let arrByID = arr.filter(filterByID); console.log("Отфильтрованный массив\n", arrByID); // Отфильтрованный массив // [< id: 15 >, < id: -1 >, < id: 3 >, < id: 12.2 >] console.log("Количество некорректных элементов token punctuation">, invalidEntries); // Количество некорректных элементов = 5 

Поиск в массиве

В следующем примере filter() используется для фильтрации содержимого массива на основе входных данных.

var fruits = ["apple", "banana", "grapes", "mango", "orange"]; /** * Элементы массива фильтруется на основе критериев поиска (query) */ function filterItems(query)  return fruits.filter(function (el)  return el.toLowerCase().indexOf(query.toLowerCase()) > -1; >); > console.log(filterItems("ap")); // ['apple', 'grapes'] console.log(filterItems("an")); // ['banana', 'mango', 'orange'] 
Реализация с использованием ES2015
const fruits = ["apple", "banana", "grapes", "mango", "orange"]; /** * Элементы массива фильтруется на основе критериев поиска (query) */ const filterItems = (arr, query) =>  return arr.filter( (el) => el.toLowerCase().indexOf(query.toLowerCase()) !== -1, ); >; console.log(filterItems(fruits, "ap")); // ['apple', 'grapes'] console.log(filterItems(fruits, "an")); // ['banana', 'mango', 'orange'] 

Модификация изначального массива (изменение, добавление и удаление)

В следующих примерах проверяется поведение метода filter при изменении массива.

// Изменение всех элементов let words = ["spray", "limit", "exuberant", "destruction", "elite", "present"]; const modifiedWords = words.filter((word, index, arr) =>  arr[index + 1] += " extra"; return word.length  6; >); console.log(modifiedWords); // Обратите внимание, что есть три слова длиной менее 6, но так как они были изменены, // возвращается одно слово ['spray'] // Добавление новых элементов words = ["spray", "limit", "exuberant", "destruction", "elite", "present"]; const appendedWords = words.filter((word, index, arr) =>  arr.push("new"); return word.length  6; >); console.log(appendedWords); // Только три слова удовлетворяют условию, хотя `words` теперь имеет куда больше слов, // длинной меньше 6 символов: ['spray', 'limit', 'elite'] // Удаление элементов words = ["spray", "limit", "exuberant", "destruction", "elite", "present"]; const deleteWords = words.filter((word, index, arr) =>  arr.pop(); return word.length  6; >); console.log(deleteWords); // Заметьте, что 'elite' не получено, так как удалено из `words` до того, // как filter смог получить его: ['spray', 'limit'] 

Спецификации

Specification
ECMAScript Language Specification
# sec-array.prototype.filter

Поддержка браузерами

BCD tables only load in the browser

Смотрите также

  • Полифил Array.prototype.filter в библиотеке core-js
  • Array.prototype.forEach()
  • Array.prototype.every()
  • Array.prototype.some()
  • Array.prototype.reduce()
  • Array.prototype.find()

Found a content problem with this page?

  • Edit the page on GitHub.
  • Report the content issue.
  • View the source on GitHub.

This page was last modified on 4 авг. 2023 г. by MDN contributors.

Your blueprint for a better internet.

jQuery QueryBuilder

Compiled and minified files with examples and sources.

Content Delivery Network

The package is available on jsDelivr.

Install with npm

You can also get all necessary files and dependencies with npm.

$ npm install jQuery-QueryBuilder

Overview

QueryBuilder is an UI component to create queries and filters.

  • It can be used on advanced search engine pages, administration backends, etc.
  • It is highly customizable and is pluggable to many jQuery widgets like autocompleters, sliders and datepickers.
  • It outputs a structured JSON of rules which can be easily parsed to create SQL/NoSQL/whatever queries.
  • And it also comes with a set of greatplugins and has a full events system for even more features.

The full code of this example can be found here.

Getting started

Dependencies

  • jQuery >= 1.10
  • Bootstrap >= 3.1 (CSS Buttons and Utilities only)
  • $.extendext
  • MomentJS (optional, for Date/Time validation)
  • Other libraries used by plugins
Don’t want to use Bootstrap ?

Let’s go!

Include query-builder.css in your page head and query-builder.js after the dependencies. Then add QueryBuilder to any you want.

 id="builder">
$('#builder').queryBuilder( filters: [ . ] >);

QueryBuilder can also be used with CommonJS :

require(['jquery', 'query-builder'], function($)  $('#builder').queryBuilder( filters: [ . ] >); >);

A standalone version is available with $.extendext included (you still need to add jQuery and Bootstrap).

Backends

Awesome people implemented parsers in various language, check them out :

  • JAVA (JDBC) itfsw / QueryBuilder
  • JAVA (JOOQ) Kowalski.io / jqb2jooq
  • .NET castle-it / dynamic-linq-query-builder
  • PHP (Doctrine ORM) fourlabsldn / QBJSParser
  • PHP (Symfony with Doctrine ORM) fourlabsldn / QBJSParserBundle
  • PHP (Illuminate, Laravel with Illuminate) timgws / QueryBuilderParser
  • PHP (Yii 2) leandrogehlen / yii2-querybuilder
  • PHP (Symfony with Doctrine ORM) josedacosta / jQueryQueryBuilderBundle
  • Python NorthIsUp / querybuilder
  • Python shunyeka / jQuery-QueryBuilder-Python-Evaluator
  • Python (SQLAlchemy ORM) ocurero / sqlalchemy-querybuilder
  • Rails SixiS / jquery_query_builder-rails
  • Go enjoei/pkg/ / querybuilder

Want your project listed here ? Open an issue or create a pull request on the gh-pages branch.

Usage

Options

Name type default description
filters object[] required Array of available filters in the builder. See below
plugins object Configuration of plugins. See plugins page
rules object Initial set of rules. It’s like calling setRules method after initialization. By default the builder will contain one empty rule.
optgroups object List of groups in the filters and operators dropdowns (see filters and operators configuration). It can be a simple id => label map or contains localized strings. More details

Simple id => label map :

optgroups:  core: '-- Core', plugins: '-- Plugins' >

Localized strings ( en is mandatory) :

optgroups:  core:  'en': '-- Core', 'fr': '-- Coeur', 'de': '-- Kern' > >

Filters

The filters option is an array of plain objects defining the rules possible contents. Here are the available attributes:

Name type default description
id string required Unique identifier of the filter.
field string =id Field used by the filter, multiple filters can use the same field.
label string =field Label used to display the filter. It can be simple string or a map for localization. More details

Define label as a map to translate the filter ( en is mandatory) :

label:  'en': 'Name', 'fr': 'Nom', 'es': 'Nombre' >
  • rule a Rule object
  • input_name the name of the input

Four formats are allowed for the values object.

    Simple array of values, labels will be the values.

values: ['one', 'two', 'three']
values:  'one': 'Un', 'two': 'Deux', 'three': 'Trois' >
values: [ 'one': 'Un'>, 'two': 'Deux'>, 'three': 'Trois'> ]
values: [  value: 'one', label: 'Un', optgroup: 'Group 1' >,  value: 'two', label: 'Deux', optgroup: 'Group 2' >,  value: 'three', label: 'Trois' > // no group ]
  • equal
  • not_equal
  • in
  • not_in
  • less
  • less_or_equal
  • greater
  • greater_or_equal
  • between
  • not_between
  • begins_with
  • not_begins_with
  • contains
  • not_contains
  • ends_with
  • not_ends_with
  • is_empty
  • is_not_empty
  • is_null
  • is_not_null
  • rule the Rule object
  • value
  • rule the Rule object

Validation

QueryBuilder integrates a configurable validation system triggered when validate() or getRules() methods are called. The default validator checks for emptyness and can be extended with format check and bounds.
Optionally you can define a custom validation callback.

Here are the available attributes of the validation field of each filter:

  • For date , time , datetime : a valid MomentJS string format
  • For string : a regular expression (plain or RegExp object)
  • For integer , double : minimum value
  • For date , time , datetime : minimum value, respecting format
  • For string : minimum length
  • For integer , double : maximum value
  • For date , time , datetime : maximum value, respecting format
  • For string : maximum length
  • For integer , double : step value (for double you should always provide this value in order to pass the browser validation on inputs).
    any is allowed to bypass browser validation.
validation:  format: /^(?:[0-9]\.)[0-9] $/, messages:  format: 'The provided IP is not valid' > >
  • value
  • rule the Rule object

Methods

The plugin’s function acts as a proxy to access all underlying methods.

$('#builder').queryBuilder('methodName', param_1, param_2);

You can also execute methods by getting a reference to the builder instance.

$('#builder')[0].queryBuilder.methodName(param_1, param_2);

Only main methods are described, consult the API documentation to learn more about all available methods.

Plugins methods

Methods added by plugins are detailed in their respective sections.

.validate([options])

Returns a boolean indicating whether the builder is valid or not. Use the validationError event to catch per-rule validation errors. If display_errors is enabled the invalid rules will turn red.

Option type default description
skip_empty boolean false true to skip the validation on rules that have no filter selected.
.getRules([options])

Performs validation and returns the rules as a plain JSON object. See the demo for output example. The method takes an optional object of options.

Option type default description
get_flags boolean|string false true to return rule and group flags that differ from the default values. ‘all’ to return all rule and group flags.
allow_invalid boolean false true to return the rules evn though the validation fails. The returned object has an additional `valid` property.
skip_empty boolean false true to skip rules that have no filter selected.
// get all rules $('#builder').queryBuilder('getRules'); // get all rules and their flags when applicable $('#builder').queryBuilder('getRules',  get_flags: true >);
Other formats
.setRules(rules [, options])

Clears the builder and sets new rules. The parameters must have the same structure as the output of getRules . See an example

Option type default description
allow_invalid boolean false true to allow loading invalid and/or incomplete rules (no operator, no value, etc.).
$('#builder').queryBuilder('setRules',  . >);

This is the data format expected by setRules method.

 "condition": "AND", "rules": [  "id": "price", "field": "price", "type": "double", "input": "text", "operator": "less", "value": "10.25" >,  "condition": "OR", "rules": [  "id": "category", "field": "category", "type": "integer", "input": "select", "operator": "equal", "value": "2" >,  "id": "category", "field": "category", "type": "integer", "input": "select", "operator": "equal", "value": "1" > ] > ] >
User data

Each rule and group can have an additional data parameter which will be merged with the filter data (for rules only) when calling getRules .

$('#builder').queryBuilder('setRules',  condition: 'AND', data:  // group data foo: 'bar' >, rules: [  /* rule definition */ data:  // rule data foo: 'bar' > > ] >);

The rule’s data will be removed if the filter of the rule is changed. You can use the flags (see bellow) to lock the filter of a rule.

Empty rules

The setRules method will throw an error if a rule has no filter. If for some reason you want to populate the builder with an empty rule, use the empty keyword.

$('#builder').queryBuilder('setRules',  condition: 'AND', rules: [  /* standard rule */ >,  /* empty rule */ empty: true > ] >);
Flags

Each rule can have an additional flags parameter which will control the editability of the rule.

Property type default description
filter_readonly boolean false The filter select box is disabled.
operator_readonly boolean false The operator select box is disabled.
value_readonly boolean false The value inputs are disabled.
no_delete boolean false The rule can’t be deleted. A group containing an undeletable rule can’t deleted.

Alternatively you can set the readonly parameter to true , which is a shorthand to:

 filter_readonly: true, operator_readonly: true, value_readonly: true, no_delete: true >

The same way, each group can have an additional flags parameter which will control the editability of the group.

Property type default description
condition_readonly boolean false The group condition can’t be changed.
no_add_rule boolean false The «Add rule» button is disabled.
no_add_group boolean false The «Add group» button is disabled.
no_delete boolean false The group can’t be deleted.

Alternatively you can set the readonly parameter to true , which is a shorthand to:

 condition_readonly: true, no_add_rule: true, no_add_group: true, no_delete: true >
.getModel([element])

Given a group or rule DOM element, returns the associated Group or Rule object. Useful to perform manual operations on the builder (see Inside the box). Without parameters it returns the root group model.

var root_model = $('#builder').queryBuilder('getModel'); var last_node_model = $('#builder').queryBuilder('getModel', $('#builder .rule-container').last());
.reset()

Removes all rules.

$('#builder').queryBuilder('reset');
.destroy()

Completely destroy the builder and it’s data.

$('#builder').queryBuilder('destroy');

Events

QueryBuilder uses jQuery events to notify the «outer world» about various things happening, like adding a rule or when a validation error happens. The events system is also used by plugins.

There are two types of events: triggers are used to identify a point in the code and changers are used to modify a value before it is used (eg: template, output rules). Both types are used the same way with the jQuery on method on the builder container.

The full list of events can be found in the API documentation.

Triggers

Some events can be cancelled by calling preventDefault() . The typical example is for the errors events :

$('#builder').on('validationError.queryBuilder', function(e, rule, error, value)  // never display error for my custom filter if (rule.filter.id == 'my_custom_filter')  e.preventDefault(); > >);
Changers

All changers events have an additional value property which holds the value to be altered (or not).

$('#builder').on('getGroupTemplate.queryBuilder.filter', function(e, level)  if (level == 1)  e.value = /* . */ > >);
Callbacks context

In all events callbacks, the first parameter is an Event object which contains the builder property, a reference to the QueryBuilder object currently used. Among other things it contains builder.settings which holds the current configuration.

Rule & Group

Read Inside the box to learn more about the Rule and Group objects.

Plugins events

Events added by plugins are detailed in their respective sections.

Themes

QueryBuilder comes with two colors-schemes: default (clear) and dark. Change the active theme by switching stylesheets. You cannot use both color-schemes on the same page.

Advanced

Operators

The operators config property is an array of strings (existing operators) or object (existing and new operators). The operators properties are :

Property type description
type string Identifier of the operator, use the lang.operators to translate or give a human readable name to your operator.
optgroup string Optional id of an in the operators dropdown. If the optgroup does not exist in the global optgroups map, it will be created with label=id for all languages.
nb_inputs int The number of inputs displayed. Typical values are 0 ( is_null & similar operators), 1 (most operators) and 2 ( between operator).
multiple boolean Inform the builder that each input can have multiple values. true for in and not_in , false otherwise.
apply_to array An array containing string , number , datetime , boolean .

For example to only use «equal» and «not equal» operators you use this config :

operators: ['equal', 'not_equal']

To use «equal» and «not equal» and a custom operator, in custom optgroups :

operators: [  type: 'equal', optgroup: 'basic' >,  type: 'not_equal', optgroup: 'basic' >,  type: 'geo', optgroup: 'custom', nb_inputs: 3, multiple: false, apply_to: ['number'] > ]

Translation

Translation files are available in the i18n folder. Just include one of the files after the main JavaScript to use it.

You can load multiple translation files and use the lang_code option to choose which language to use.

Available languages are (some are partially translated) :

Albanian Arabic Azerbaijani Bulgarian Simplified Chinese Czech Danish Dutch English Farsi French German Greek Hebrew Italian Norwegian Polish Portuguese Brazilian Portuguese Romanian Russian Spanish Turkish Ukrainian

Alternatively you can overwrite some translations with the lang option. It is very useful for custom operators and conditions.
Default English strings are in the source code .

Icons

The icons option provides a way of using alternate icons sets. Available attributes:

Name type default
add_group string ‘glyphicon glyphicon-plus-sign’
add_rule string ‘glyphicon glyphicon-plus’
remove_group string ‘glyphicon glyphicon-remove’
remove_rule string ‘glyphicon glyphicon-remove’
error string ‘glyphicon glyphicon-warning-sign’

Templates

For very specific customizations, QueryBuilder provides a way to completely overwrite the HTML templates used to display rules and groups. It uses the JS template litterals by default, but can be used with most JS template engines, like underscore.js one.

Very advanced feature

Modifying templates can lead to a non-functionnal builder if the general layout differs too much. In particular, non-Bootstrap CSS classes should not be removed.

Templates must be provided as a function taking an object of variables and returning an HTML string ( _.template for instance). Check the default templates in the source code.

For all templates, these variables are available :

  • builder reference to the QueryBuilder object
  • settings short-hand for builder.settings
  • lang short-hand for builder.settings.lang
  • icons short-hand for builder.settings.icons
group

The template used to build an empty group. Other variables available :

  • group_id unique identifier of the group
  • level level of the group (1 is root)
  • conditions the conditions available in this group
rule

The template used to build an empty rule. Other variables available :

  • rule_id unique identifier of the rule
filterSelect

The template used to build the filters selectbox. Other variables available :

  • rule a Rule object
  • filters the filters available in this rule
  • translate a function used for localization
operatorSelect

The template used to build the operators selectbox. Other variables available :

  • rule a Rule object
  • operators the operators available in this rule
  • translate a function used for localization

Inside the box

You might have noticed that callbacks and events refer to two objects Rule and Group. These objects are part of the data model with partial data-binding used internally by QueryBuilder. Here are the structures of these two objects. Most attributes will live-update the builder when modified.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *