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 great plugins and has a full events system for even more features.
The full code of this example can be found here.
Getting started
Download jQuery QueryBuilderDependencies
- 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 see what we can do for you.
Let's go!
Include query-builder.css in your page head and
query-builder.js after the dependencies. Then add QueryBuilder to any <div>
you want.
QueryBuilder can also be used with CommonJS :
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 : Localized strings ( |
|
default_filter | string | null | The id of the default filter for any new rule. |
sort_filters | boolean|function | false | Sort filters alphabetically, or with a custom function (passed to Array.sort ). |
allow_groups | boolean|int | true | Number of allowed nested groups. true for no limit. |
allow_empty | boolean | false | No error will be thrown is the builder is entirely empty. |
display_errors | boolean | true | When an error occurs on a rule, display an icon with a tooltip explaining the error. |
conditions | string[] | ['AND', 'OR'] | Array of available group conditions. Use the lang option to change the label. |
default_condition | string | 'AND' | Default active condition. |
inputs_separator | string | ' , ' | Piece of HTML used to separate multiple inputs (for between operator). |
display_empty_filter | boolean | true | Add an empty option with select_placeholder string to the filter dropdowns. If the empty filter
is disabled and no default_filter is defined, the first filter will be loaded when adding a rule.
|
select_placeholder | string | '------' | Label of the "no filter" option. |
operators | object[] | Configuration of operators. See below | |
lang_code | string | 'en' | One of the language files code available. Default is English or the last loaded language. |
lang | object | Additional/overwrites translation strings. See below | |
icons | object | glyphicons | Font-icons used in the builder. Defaults to using Glyphicons. See below |
templates | object | HTML templates. See below |
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 |
optgroup | string|object | Optional id of an <optgroup> in the filters dropdown. If the optgroup does not exist in
the global optgroups map, it will be created with label=id for all languages.
|
|
type | string | required | Type of the field. Available types are string , integer , double ,
date , time , datetime and boolean .
|
input | string|function | 'text'|'number' | Type of input used. Available types are text , number , textarea ,
radio , checkbox and select .It can also be a function which returns the HTML of the said input, this function takes 2 parameters:
|
values | array|object | required* | Required for radio and checkbox inputs. Generally needed for
select inputs.
More details
Four formats are allowed for the
|
value_separator | string | Used the split and join the value when a text input is used with an operator allowing multiple
values (between for example).
|
|
default_value | mixed | As it says :-) | |
input_event | string | 'change' | Space separated list of DOM events which the builder should listen to detect value changes. |
size | int | Only for text and textarea inputs: horizontal size of the input. |
|
rows | int | Only for textarea inputs: vertical size of the input. |
|
multiple | boolean | false | Only for select inputs: accept multiple values. |
placeholder | string | Only for text and textarea inputs: placeholder to display inside the input.
|
|
vertical | boolean | false | Only for radio and checkbox inputs: display inputs vertically on not
horizontally.
|
validation | object | Object of options for rule validation. See below | |
operators | array | Array of operators types to use for this filter. If empty the filter will use all applicable operators.
Show all operators
|
|
default_operator | string | operators[0] |
Type code of the default operator for this filter. |
plugin | string | Name of a jQuery plugin to apply on the input. | |
plugin_config | object | Object of parameters to pass to the plugin. | |
data | object | Additional data not used by QueryBuilder but that will be added to the output rules object. Use this to store any functional data you need. | |
valueSetter | function | Function used to set the input(s) value. If provided the default function is not run. It takes 2 parameters:
|
|
valueGetter | function | Function used to get the input(s) value. If provided the default function is not run. It takes 1 parameter:
|
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:
Name | type | description |
---|---|---|
format | string|object |
|
min | integer|double|string |
|
max | integer|double|string |
|
step | integer|double |
|
messages | object | Custom error messages for the standard validations, keys are validation names. |
allow_empty_value | boolean | true to allow empty user input for this filter |
callback | function | A function used to perform the validation. If provided, the default validation will not be performed. It
must returns true if the value is valid or an error string otherwise. It takes 2 parameters:
|
Methods
The plugin's function acts as a proxy to access all underlying methods.
You can also execute methods by getting a reference to the builder instance.
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.
|
Other formats
For other output formats like SQL and MongoDB, please refer to the plugins page.
.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.). |
This is the data format expected by setRules
method.
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
.
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.
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:
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:
.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.
.reset()
Removes all rules.
.destroy()
Completely destroy the builder and it's data.
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 :
Changers
All changers events have an additional value
property which holds the value to be altered (or not).
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
QueryBuilder is bundled with an extensive list of operators. You can change which operators are available for each filter (see filters configuration) but you can also modify/reorder the operators globally and even add new custom 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 <optgroup> 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 :
To use "equal" and "not equal" and a custom operator, in custom optgroups :
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) :
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 objectsettings
short-hand for builder.settingslang
short-hand for builder.settings.langicons
short-hand for builder.settings.icons
group
The template used to build an empty group. Other variables available :
group_id
unique identifier of the grouplevel
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 objectfilters
the filters available in this ruletranslate
a function used for localization
operatorSelect
The template used to build the operators selectbox. Other variables available :
rule
a Rule objectoperators
the operators available in this ruletranslate
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.