### Example RulesJSON Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/types.md A complete example demonstrating a RulesJSON structure with nested groups and various rule types. ```javascript { valid: true, condition: 'AND', rules: [ { id: 'name', field: 'user_name', type: 'string', input: 'text', operator: 'contains', value: 'John' }, { condition: 'OR', rules: [ { id: 'age', field: 'user_age', type: 'integer', input: 'number', operator: 'greater', value: 30 }, { id: 'status', field: 'user_status', type: 'string', input: 'select', operator: 'in', value: ['active', 'pending'] } ] } ] } ``` -------------------------------- ### Install jQuery QueryBuilder with npm Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/README.md Use npm to install the jQuery QueryBuilder package. This is a common method for managing project dependencies. ```bash npm install jQuery-QueryBuilder ``` -------------------------------- ### Extend Filter Configuration with Description Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/plugins.md This example shows how to extend the filter configuration to include a description. This description will be displayed in the UI by the 'filter-description' plugin. ```javascript { id: 'status', label: 'Status', description: 'User account status', // plugin displays this description in UI } ``` -------------------------------- ### Common QueryBuilder Filter Usage Example Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/types.md An example demonstrating a common filter configuration for a 'User Name' field. It specifies the field's ID, backend name, display label, data type, input type, and validation rules. ```javascript { id: 'name', field: 'user_name', label: 'User Name', type: 'string', input: 'text', default_value: '', validation: { min: 1, max: 100, format: '^[a-zA-Z ]+$' } } ``` -------------------------------- ### Import QueryBuilder Rules Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/INDEX.md Shows how to set rules into the QueryBuilder using simple or grouped formats. Includes an example of importing rules from a SQL string. ```javascript // Simple format $('#builder').queryBuilder('setRules', [ {id: 'name', operator: 'equal', value: 'John'}, {id: 'age', operator: 'greater', value: 18} ]); // Group format with nesting $('#builder').queryBuilder('setRules', { condition: 'AND', rules: [ {id: 'name', operator: 'contains', value: 'John'}, { condition: 'OR', rules: [ {id: 'age', operator: 'greater', value: 30}, {id: 'status', operator: 'equal', value: 'active'} ] } ] }); // From SQL (requires sql-support plugin) $('#builder').queryBuilder('sqlToRules', "(name LIKE 'John%') AND (age > 18)"); ``` -------------------------------- ### QueryBuilder afterInit Event Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/events.md Listen for the `afterInit` event, which fires after the builder is fully initialized and just before the root group is created. This is useful for performing actions immediately after setup. ```javascript $('#builder').queryBuilder('on', 'afterInit', function() { console.log('Builder initialized'); }); ``` -------------------------------- ### QueryBuilder Initialization and Method Call Example Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/api-reference.md Demonstrates initializing the QueryBuilder with specific filters and then calling the 'getRules' method on the instance. It also shows how to access the instance directly using jQuery's data method. ```javascript $('#builder').queryBuilder({ filters: [ {id: 'name', label: 'Name', type: 'string'}, {id: 'age', label: 'Age', type: 'integer'} ] }); // Call method on instance $('#builder').queryBuilder('getRules'); // Access the instance directly var instance = $('#builder').data('queryBuilder'); ``` -------------------------------- ### Example: Highlight Invalid Rules Plugin Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/plugins.md This example demonstrates defining a plugin that visually highlights invalid rules. It listens for validation changes and applies/removes a CSS class accordingly. The plugin can be configured with a custom highlight color. ```javascript // Define plugin QueryBuilder.define('highlight-invalid', function(options) { this.on('changer:validate', function(e) { if (!e.value) { this.$el.find('.rule-container').addClass('is-invalid'); } else { this.$el.find('.rule-container').removeClass('is-invalid'); } }); }, { highlight_color: 'red' }); // Use plugin $('#builder').queryBuilder({ plugins: { 'highlight-invalid': { highlight_color: 'orange' } } }); ``` -------------------------------- ### Log Successful Rule Loading Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/events.md Fired after `setRules()` completes. This example logs a message to the console upon successful loading of rules. ```javascript $("#builder").queryBuilder("on", "afterSetRules", function() { console.log("Rules loaded successfully"); }); ``` -------------------------------- ### Catching QueryBuilder Configuration Errors Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/errors.md This example demonstrates how to catch a `ConfigError` that occurs during QueryBuilder initialization due to invalid configuration, such as an empty filters list. It logs the error name and message to the console. ```javascript try { $("#builder").queryBuilder({ filters: [] }); } catch (e) { console.error(e.name, e.message); } ``` -------------------------------- ### Access Plugin Options Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/plugins.md Retrieve plugin options using the getPluginOptions method. You can get all options for a plugin or a specific option by its key. ```javascript var qb = $('#builder').data('queryBuilder'); var options = qb.getPluginOptions('plugin-name'); var option = qb.getPluginOptions('plugin-name', 'option1'); ``` -------------------------------- ### Add and Remove Filters Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/examples/index.html Dynamically modifies the available filters in the query builder. This example adds a new filter and removes existing ones. ```javascript // set filters $('.set-filters').on('click', function() { $(this).prop('disabled', true); bootstrap.Tooltip.getInstance($(this)).hide(); // add a new filter after 'state' $('#builder').queryBuilder('addFilter', { id: 'new_one', label: 'New filter', type: 'string' }, 'state' ); // remove filter 'coord' $('#builder').queryBuilder('removeFilter', ['coord', 'state', 'bson'], true ); // also available : 'setFilters' }); ``` -------------------------------- ### Manage QueryBuilder Rules and Groups Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/INDEX.md Provides examples for managing rules within the QueryBuilder, including resetting, clearing, adding, deleting rules, and adding/deleting subgroups. ```javascript // Reset to one empty rule $('#builder').queryBuilder('reset'); // Clear all rules $('#builder').queryBuilder('clear'); // Add rule to group var root = $('#builder').queryBuilder('getModel'); $('#builder').queryBuilder('addRule', root); // Delete rule var rule = $('#builder').queryBuilder('getModel', $('.rule-container').first()); $('#builder').queryBuilder('deleteRule', rule); // Add subgroup var newGroup = $('#builder').queryBuilder('addGroup', root); // Delete subgroup $('#builder').queryBuilder('deleteGroup', newGroup); ``` -------------------------------- ### Get Query Rules Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/README.md Retrieve the current set of rules from the query builder instance. This is useful for saving or processing the query. ```javascript var rules = $('#builder').queryBuilder('getRules'); console.log(JSON.stringify(rules)); ``` -------------------------------- ### Listen to QueryBuilder Events with jQuery Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/events.md Demonstrates multiple ways to attach event listeners to the QueryBuilder instance using jQuery's `.on()` method, the queryBuilder's `on()` method, and direct instance method calls. Includes a one-time listener example. ```javascript $('#builder').on('afterAddRule.queryBuilder', function(e, rule) { console.log('Rule added:', rule); }); ``` ```javascript $('#builder').queryBuilder('on', 'afterAddRule', function(e, rule) { console.log('Rule added:', rule); }); ``` ```javascript var qb = $('#builder').data('queryBuilder'); vqb.on('afterAddRule', function(e, rule) { console.log('Rule added:', rule); }); ``` ```javascript $('#builder').queryBuilder('once', 'afterSetRules', function() { console.log('Rules loaded once'); }); ``` -------------------------------- ### Set and Get QueryBuilder Defaults Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/api-reference.md Use QueryBuilder.defaults to set global default configurations for all new QueryBuilder instances or to retrieve specific default options or the entire defaults object. ```javascript $.fn.queryBuilder.defaults({ allow_empty: true, default_condition: 'OR' }); // Get specific default option var allowEmpty = $.fn.queryBuilder.defaults('allow_empty'); // Get full defaults object var allDefaults = $.fn.queryBuilder.defaults(); ``` -------------------------------- ### once(type, callback) Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/api-reference.md Attaches an event listener that fires only once, then is automatically removed. This is useful for one-time setup or actions that should only occur the first time an event is triggered. ```APIDOC ## once(type, callback) ### Description Attaches an event listener that fires only once, then is automatically removed. ### Method ```javascript once(type, callback) ``` ### Parameters #### Path Parameters - **type** (string) - Required - Event type - **callback** (function) - Required - Handler function ### Returns - **QueryBuilder** - this (for chaining) ### Example ```javascript $("#builder").queryBuilder('once', 'afterSetRules', function() { console.log('Rules loaded once'); }); ``` ``` -------------------------------- ### QueryBuilder.defaults(options) Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/api-reference.md Gets or modifies the default configuration for all new QueryBuilder instances. It can be used to set global default options or retrieve specific default values or the entire defaults object. ```APIDOC ## QueryBuilder.defaults(options) ### Description Gets or modifies the default configuration for all new instances. ### Method Static ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options** (object | string) - Optional - Configuration object to merge with defaults, or a property name to retrieve ### Request Example ```javascript // Set defaults for all new instances $.fn.queryBuilder.defaults({ allow_empty: true, default_condition: 'OR' }); // Get specific default option var allowEmpty = $.fn.queryBuilder.defaults('allow_empty'); // Get full defaults object var allDefaults = $.fn.queryBuilder.defaults(); ``` ### Response #### Success Response (200) - **Configuration object/value** (object | *) - Configuration object/value (if getting) - **undefined** - undefined (if setting) #### Response Example ```json { "allow_empty": true, "default_condition": "OR" } ``` ``` -------------------------------- ### Save and Load Rules via AJAX Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/advanced-usage.md Save rules to the server by sending a JSON payload to a POST endpoint. Load rules from the server by making a GET request to retrieve rules and then setting them in the query builder. ```javascript // Save rules to server function saveRules() { var rules = $('#builder').queryBuilder('getRules'); $.ajax({ url: '/api/queries', method: 'POST', data: JSON.stringify(rules), contentType: 'application/json', success: function(response) { alert('Rules saved successfully'); } }); } // Load rules from server function loadRules(id) { $.ajax({ url: '/api/queries/' + id, method: 'GET', success: function(rules) { $('#builder').queryBuilder('setRules', rules); } }); } ``` -------------------------------- ### Enable Plugins with Object Format and Options Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/configuration.md Configure plugins and their specific options by passing an object to the 'plugins' configuration. An empty object enables the plugin with default settings. ```javascript // Object format with options $('#builder').queryBuilder({ plugins: { 'sql-support': { boolean_as_integer: false }, 'sortable': {} } }); ``` -------------------------------- ### SQL Export with Plugin Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/README.md Initialize the query builder with the 'sql-support' plugin to enable SQL export functionality. Then, retrieve the rules formatted as SQL. ```javascript $('#builder').queryBuilder({ plugins: ['sql-support'] }); var sql = $('#builder').queryBuilder('getRulesAsSQL'); // Execute on backend ``` -------------------------------- ### Basic Initialization Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/README.md Initialize the query builder with a list of filters. Use this to set up the available fields and their types for building queries. ```javascript $('#builder').queryBuilder({ filters: [ {id: 'name', label: 'Name', type: 'string', input: 'text'}, {id: 'age', label: 'Age', type: 'integer', input: 'number'} ] }); ``` -------------------------------- ### Get Rules as JSON Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/examples/index.html Retrieves the current set of rules from the QueryBuilder and displays them as a formatted JSON string. ```javascript $('.parse-json').on('click', function() { $('#result').removeClass('d-none') .find('pre').html(JSON.stringify( $('#builder').queryBuilder('getRules', { get_flags: true, skip_empty: true }), undefined, 2 )); }); ``` -------------------------------- ### Enable Plugins with Array Format Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/configuration.md Activate multiple plugins by providing their names in an array to the 'plugins' configuration option. ```javascript // Array format $('#builder').queryBuilder({ plugins: ['sql-support', 'bt-tooltip-errors'] }); ``` -------------------------------- ### Get Filter by ID Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/api-reference.md Retrieves a filter configuration object by its ID. Use this to access specific filter settings. ```javascript var filter = $('#builder').queryBuilder('getFilterById', 'name'); console.log(filter.label); ``` -------------------------------- ### Initialize QueryBuilder with Options Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/configuration.md Basic initialization of the QueryBuilder plugin by passing an options object to the constructor. Use this to set initial filters and control basic behavior like allowing empty root groups. ```javascript $('#builder').queryBuilder({ filters: [...], allow_empty: false, // ... more options }); ``` -------------------------------- ### Initialize QueryBuilder and Handle Events Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/INDEX.md Basic initialization of the QueryBuilder with filters. Shows how to add an event listener for rule changes and retrieve current rules. ```javascript // Basic initialization $('#builder').queryBuilder({ filters: [ {id: 'name', label: 'Name', type: 'string', input: 'text'}, {id: 'age', label: 'Age', type: 'integer', input: 'number'} ] }); // Add event listener $('#builder').queryBuilder('on', 'afterSetRules', function() { console.log('Rules loaded'); }); // Get current rules var rules = $('#builder').queryBuilder('getRules'); console.log(JSON.stringify(rules)); ``` -------------------------------- ### Translate Text Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/api-reference.md Returns a translated string from the language definitions. Use this to get localized labels for conditions, operators, or error messages. ```javascript var conditionLabel = $('#builder').queryBuilder('translate', 'conditions', 'AND'); var errorMsg = $('#builder').queryBuilder('translate', 'errors', 'empty_group'); ``` -------------------------------- ### Get Root Group Model Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/api-reference.md Retrieves the root group model object for the query builder. This is the top-level container for all rules and groups. ```javascript // Get root group var root = $('#builder').queryBuilder('getModel'); ``` -------------------------------- ### Prevent Adding Group at Max Depth Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/events.md Fired before a subgroup is added. This example prevents adding a group if the nesting level reaches 3. ```javascript $("#builder").queryBuilder("on", "beforeAddGroup", function(e, parent, addRule, level) { if (level >= 3) { e.preventDefault(); alert("Maximum nesting depth reached"); } }); ``` -------------------------------- ### Use a QueryBuilder Plugin (Object Format) Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/plugins.md Activate a registered plugin with custom options by specifying it in the 'plugins' configuration as an object. ```javascript // Object format (with custom options) $('#builder').queryBuilder({ plugins: { 'plugin-name': { option1: 'value1' } } }); ``` -------------------------------- ### afterInit Event Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/events.md Fired when the builder is fully initialized, just before the root group is created. This event does not accept any parameters. ```APIDOC ## afterInit Event ### Description Fired when the builder is fully initialized, just before the root group is created. ### Parameters None ### Example ```javascript $('#builder').queryBuilder('on', 'afterInit', function() { console.log('Builder initialized'); }); ``` ``` -------------------------------- ### Use a QueryBuilder Plugin (Array Format) Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/plugins.md Activate a registered plugin using the 'plugins' configuration option in an array format, which applies default plugin options. ```javascript // Array format (uses default options) $('#builder').queryBuilder({ plugins: ['plugin-name'] }); ``` -------------------------------- ### Get Operator by Type Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/api-reference.md Retrieves an operator configuration object by its type. Useful for inspecting operator properties like the number of inputs required. ```javascript var operator = $('#builder').queryBuilder('getOperatorByType', 'contains'); console.log(operator.nb_inputs); // 1 ``` -------------------------------- ### Get Specific Rule/Group Model Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/api-reference.md Retrieves the model object (Rule or Group) associated with a specific DOM element within the query builder. ```javascript // Get model from DOM element var $rule = $('#builder').find('.rule-container').first(); var rule = $('#builder').queryBuilder('getModel', $rule); ``` -------------------------------- ### Configure and Use QueryBuilder Plugins Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/INDEX.md Demonstrates how to enable and configure plugins for jQuery QueryBuilder, such as SQL support, sortable, and tooltips. Plugin features can be accessed after enabling. ```javascript // Enable plugins $('#builder').queryBuilder({ plugins: { 'sql-support': {}, 'sortable': {}, 'bt-tooltip-errors': {} } }); // Use plugin features var sql = $('#builder').queryBuilder('getRulesAsSQL'); // Configure plugin $('#builder').queryBuilder({ plugins: { 'chosen-selectpicker': { allow_single_deselect: true, width: '100%' } } }); ``` -------------------------------- ### Define and Use a Custom jQuery QueryBuilder Plugin Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/INDEX.md Demonstrates how to define a custom plugin for jQuery QueryBuilder, including adding methods, listening to events, and applying styles. Shows how to instantiate the builder with the custom plugin. ```javascript QueryBuilder.define('my-plugin', function(options) { // Add method to builder instance this.myCustomMethod = function() { return 'custom result'; }; // Listen to events this.on('afterAddRule', function(e, rule) { console.log('Rule added:', rule.id); }); // Add styles or features this.$el.addClass('has-my-plugin'); }, { // Default options option1: 'default_value' }); // Use plugin $('#builder').queryBuilder({ plugins: { 'my-plugin': { option1: 'custom_value' } } }); ``` -------------------------------- ### Constructor Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/DOCUMENTATION_MANIFEST.txt Initializes a new instance of the QueryBuilder on a target DOM element. Accepts an options object to configure its behavior. ```APIDOC ## Constructor ### Description Initializes a new instance of the QueryBuilder on a target DOM element. Accepts an options object to configure its behavior. ### Method JavaScript (jQuery plugin) ### Endpoint N/A (jQuery plugin) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript $("#builder").queryBuilder(options); ``` ### Response #### Success Response (200) N/A (initialization) #### Response Example N/A ``` -------------------------------- ### Core Methods Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/INDEX.md Provides methods for managing the builder's lifecycle, state, and configuration. ```APIDOC ## Core Methods ### Description Methods for cleaning up, resetting, clearing, modifying options, validating, exporting/importing rules, and accessing the rule/group model. ### Methods - `destroy()`: Clean up and remove builder. - `reset()`: Clear and reset to initial state. - `clear()`: Remove all rules. - `setOptions(options)`: Modify configuration at runtime. - `validate()`: Check all rules are valid. - `getRules()`: Export rules as JSON. - `setRules(rules)`: Import rules from JSON. - `getModel(element)`: Get Rule/Group model from DOM. ``` -------------------------------- ### Initialize QueryBuilder with Configuration Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/api-reference.md Use this snippet to initialize the QueryBuilder plugin with a set of filters. The configuration object is passed as the first argument to the jQuery plugin. ```javascript $.fn.queryBuilder(option, ...args) ``` -------------------------------- ### Get Applicable Operators for a Filter Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/api-reference.md Returns a list of operators that are applicable to a given filter. This is useful for dynamically updating UI elements based on filter type. ```javascript var filter = $('#builder').queryBuilder('getFilterById', 'age'); var operators = $('#builder').queryBuilder('getOperators', filter); operators.forEach(function(op) { console.log(op.type, op.label); }); ``` -------------------------------- ### Prevent Adding Rule with beforeAddRule Event Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/events.md Use the 'beforeAddRule' event to intercept rule additions. This example prevents adding more than 10 rules to a group by calling `e.preventDefault()`. ```javascript $("#builder").queryBuilder("on", "beforeAddRule", function(e, parent) { if (parent.rules.length >= 10) { e.preventDefault(); alert("Maximum 10 rules per group"); } }); ``` -------------------------------- ### Instance Methods Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/DOCUMENTATION_MANIFEST.txt Provides access to 40+ methods that operate on a QueryBuilder instance, allowing manipulation of rules, groups, and other aspects of the builder. ```APIDOC ## Instance Methods ### Description Provides access to 40+ methods that operate on a QueryBuilder instance, allowing manipulation of rules, groups, and other aspects of the builder. ### Method JavaScript (jQuery plugin instance methods) ### Endpoint N/A (jQuery plugin instance methods) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript var builder = $("#builder").queryBuilder('getRules'); ``` ### Response #### Success Response (200) Depends on the method called. #### Response Example Depends on the method called. ``` -------------------------------- ### Get Validation Errors from DOM Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/errors.md Retrieves validation errors associated with a specific rule element in the DOM. The error is returned as an array containing the error code and its parameters. ```javascript var $rule = $('#builder').find('.rule-container').first(); var rule = $('#builder').queryBuilder('getModel', $rule); if (rule.error) { console.log('Rule error:', rule.error); // error is array: [error_code, ...params] } ``` -------------------------------- ### Utils.fmt(str, args) Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/advanced-usage.md Formats a string by replacing numbered placeholders (e.g., {0}, {1}) with corresponding values from an array or arguments object. Useful for dynamic string creation. ```APIDOC ## Utils.fmt(str, args) ### Description Formats a string by replacing numbered placeholders with arguments. ### Parameters #### Path Parameters * **str** (string) - Required - String with {0}, {1}, etc. placeholders. * **args** (array | arguments) - Required - Values to substitute. ### Request Example ```javascript Utils.fmt('{0} is {1}', ['John', 'tall']); ``` ### Response #### Success Response - **formatted_string** (string) - The string with placeholders replaced by arguments. ### Response Example ``` John is tall ``` ``` -------------------------------- ### QueryBuilder Class Constructor Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/api-reference.md Illustrates the direct instantiation of the QueryBuilder class, requiring a jQuery-wrapped DOM element and an optional options object for configuration. ```javascript new QueryBuilder($el, options) ``` -------------------------------- ### Configure Custom Input Filter with Getter/Setter Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/INDEX.md Define a filter with a custom input element, specifying functions to get and set its value. Use for complex or non-standard input fields. ```javascript { id: 'custom', type: 'string', input: function(rule, $input) { return ''; }, valueGetter: function(rule) { return rule.$el.find('input').val(); }, valueSetter: function(rule, value) { rule.$el.find('input').val(value); } } ``` -------------------------------- ### Define a Basic Custom Plugin Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/plugins.md Use `QueryBuilder.define` to create a new plugin. This function accepts the plugin name, a callback for instance methods and event handlers, and an optional object for default options. ```javascript QueryBuilder.define('my-plugin', function(options) { // this = QueryBuilder instance // Add methods this.myMethod = function() { // Method code }; // Attach event handlers this.on('afterAddRule', function(e, rule) { // Handler code }); }, { // Default options option1: 'default_value' }); ``` -------------------------------- ### Silent Mode for Rules Parsing Errors Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/errors.md This example shows how to use silent mode to log invalid data instead of throwing an error during setRules. This is useful for non-critical data validation. ```javascript // Silent mode logs errors instead of throwing $('#builder').queryBuilder('setRules', invalidData, { allow_invalid: true }); // Invalid data is logged but doesn't throw ``` -------------------------------- ### Global Error Handling with Try-Catch Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/errors.md Use a try-catch block to handle errors during the initialization of the query builder. ```javascript try { $('#builder').queryBuilder(config); } catch (e) { console.error('Configuration failed:', e.name, e.message); } ``` -------------------------------- ### Initialize QueryBuilder with Options Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/examples/index.html Initializes the jQuery QueryBuilder plugin with a set of predefined filter options. ```javascript var options = { filters: [ { id: 'rate', label: 'Rate', icon: 'bi-box-arrow-lightning-charge-fill', type: 'integer', validation: { min: 0, max: 100 }, plugin: 'slider', plugin_config: { min: 0, max: 100, value: 0 }, valueSetter: function(rule, value) { var input = rule.$el.find('.rule-value-container input'); input.slider('setValue', value); input.val(value); // don't know why I need it } }, /* * placeholder and regex validation */ { id: 'id', label: 'Identifier', icon: 'bi-sunglasses', type: 'string', optgroup: 'plugin', placeholder: '____-____-____', size: 14, operators: ['equal', 'not_equal'], validation: { format: /^.{4}-.{4}-.{4}$/, messages: { format: 'Invalid format, expected: AAAA-AAAA-AAAA' } } }, /* * custom input */ { id: 'coord', label: 'Coordinates', icon: 'bi-star', type: 'string', default_value: 'C.5', description: 'The letter is the cadran identifier:\ ', validation: { format: /^[A-C]{1}.[1-6]{1}$/ }, input: function(rule, name) { var $container = rule.$el.find('.rule-value-container'); $container.on('change', '[name=' + name + '_1]', function() { var h = ''; switch ($(this).val()) { case 'A': h = ' '; break; case 'B': h = ' '; break; case 'C': h = ' '; break; } $container.find('[name$=' + '_2]').html(h).toggle(!!h).val('-1').trigger('change'); }); return '\ \ '; }, valueGetter: function(rule) { return rule.$el.find('.rule-value-container [name$=' + '_1]').val() + '.' + rule.$el.find('.rule-value-container [name$=' + '_2]').val(); }, valueSetter: function(rule, value) { if (rule.operator.nb_inputs > 0) { var val = value.split('.'); rule.$el.find('.rule-value-container [name$=' + '_1]').val(val[0]).trigger('change'); rule.$el.find('.rule-value-container [name$=' + '_2]').val(val[1]).trigger('change'); } } } ] }; // init $('#builder').queryBuilder(options); ``` -------------------------------- ### Get QueryBuilder Rules as JSON Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/api-reference.md Exports the current rules of the QueryBuilder as a JSON object. Supports options to include flags, allow invalid rules, and skip empty rules during export. ```javascript var rules = $('#builder').queryBuilder('getRules'); if (rules.valid) { console.log(JSON.stringify(rules)); } // Include flags in export var rulesWithFlags = $('#builder').queryBuilder('getRules', { get_flags: true }); ``` -------------------------------- ### Inspect Rules Structure in jQuery QueryBuilder Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/advanced-usage.md Recursively logs the structure of the query builder's rules and groups. Call this function to get a detailed overview of the current query configuration. ```javascript function debugRules(indent = 0) { var qb = $("#builder").data("queryBuilder"); var root = qb.getModel(); var prefix = ' '.repeat(indent); console.log(prefix + 'GROUP (' + root.condition + ')'); root.each(function(rule) { console.log(prefix + ' RULE: ' + (rule.filter ? rule.filter.label : 'empty') + ' ' + (rule.operator ? rule.operator.type : 'empty') + ' ' + rule.value); }, function(group) { debugRules(indent + 1); }); } debugRules(); ``` -------------------------------- ### Get Filter Safely (Silent Errors) Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/README.md Use this pattern to retrieve a filter by its ID without throwing an error if it's not found. It returns null instead, allowing for graceful handling. ```javascript // Don't throw, return null instead var filter = $('#builder').queryBuilder('getFilterById', 'missing', false); if (!filter) { console.log('Filter not found'); } ``` -------------------------------- ### Format String with Placeholders Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/advanced-usage.md Use Utils.fmt to substitute numbered placeholders (e.g., {0}, {1}) in a string with provided arguments. Useful for dynamic string creation. ```javascript Utils.fmt('{0} is {1}', ['John', 'tall']); // Returns: 'John is tall' Utils.fmt('{0} {1} {0}', ['hello', 'world']); // Returns: 'hello world hello' ``` -------------------------------- ### Get Node's Position in Parent Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/advanced-usage.md The `getPos()` method returns the 0-based index of a node within its parent's `rules` array. This can be helpful for understanding the order of elements in the query structure. ```javascript var rule = group.rules[1]; console.log(rule.getPos()); // 1 (0-based position in parent) ``` -------------------------------- ### Export QueryBuilder Rules as SQL Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/INDEX.md Shows how to retrieve the current QueryBuilder rules formatted as a SQL query string. This SQL should be executed on the backend. ```javascript var sql = $("#builder").queryBuilder("getRulesAsSQL"); // Execute on backend ``` -------------------------------- ### Get Number of Direct Children Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/advanced-usage.md The `length()` method returns the total count of direct child elements (both rules and subgroups) within a group. This provides a quick way to assess the immediate complexity of a group. ```javascript var root = $("#builder").queryBuilder('getModel'); console.log(root.length()); // Number of direct children (rules + groups) ``` -------------------------------- ### Retrieving Plugin Options Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/plugins.md Within a plugin, you can access the options passed during initialization or later using `this.getPluginOptions('plugin-name')`. The `options` parameter in the define callback provides initial access. ```javascript QueryBuilder.define('my-plugin', function(options) { // options = configuration passed by user var opt1 = options.option1; // Or later: var opts = this.getPluginOptions('my-plugin'); }); ``` -------------------------------- ### Integrate with HTML Forms for Rule Submission Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/advanced-usage.md Export rules when a form submits by getting the current rules and storing them as a JSON string in a hidden input field. Import rules on form load by parsing a JSON string from a hidden input. ```javascript // Export rules when form submits $('form').on('submit', function(e) { var rules = $('#builder').queryBuilder('getRules'); if (!rules.valid) { e.preventDefault(); alert('Fix validation errors'); return false; } // Store as hidden input $('input[name="query"]').val(JSON.stringify(rules)); }); // Import rules on form load $(document).ready(function() { var savedRules = $('input[name="query"]').val(); if (savedRules) { $('#builder').queryBuilder('setRules', JSON.parse(savedRules)); } }); ``` -------------------------------- ### Select with Optgroups Configuration Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/configuration.md Defines a select dropdown input that supports organizing options into optgroups. ```javascript { id: 'product', type: 'string', input: 'select', values: [ { value: 'iphone', label: 'iPhone', optgroup: 'Apple' }, { value: 'ipad', label: 'iPad', optgroup: 'Apple' }, { value: 'galaxy', label: 'Galaxy', optgroup: 'Samsung' } ] } ``` -------------------------------- ### Define a New QueryBuilder Plugin Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/api-reference.md Register a new plugin with QueryBuilder using QueryBuilder.define. This method takes the plugin name, an initialization function, and optional default configuration. ```javascript $.fn.queryBuilder.define('my-plugin', function(options) { // Plugin code }, { option1: 'default_value' }); ``` -------------------------------- ### Initialize jQuery QueryBuilder with Default Options Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/examples/index.html Basic initialization of the QueryBuilder with common options like allowing empty rules and sorting filters. It also configures custom operator groups and enables several plugins. ```javascript var $b = $("#builder"); var options = { allow_empty: true, //default_filter: 'name', sort_filters: true, optgroups: { core: { en: 'Core', fr: 'Coeur' } }, plugins: { 'bt-tooltip-errors': { delay: 100 }, 'sortable': null, 'filter-description': { mode: 'bootbox' }, // 'chosen-selectpicker': null, 'unique-filter': null, 'bt-checkbox': { color: 'primary' }, 'invert': null, 'not-group': null }, // standard operators in custom optgroups operators: [ { type: 'equal', optgroup: 'basic' }, { type: 'not_equal', optgroup: 'basic' }, { type: 'in', optgroup: 'basic' }, { type: 'not_in', optgroup: 'basic' }, { type: 'less', optgroup: 'numbers' }, { type: 'less_or_equal', optgroup: 'numbers' }, { type: 'greater', optgroup: 'numbers' }, { type: 'greater_or_equal', optgroup: 'numbers' }, { type: 'between', optgroup: 'numbers' }, { type: 'not_between', optgroup: 'numbers' }, { type: 'begins_with', optgroup: 'strings' }, { type: 'not_begins_with', optgroup: 'strings' }, { type: 'contains', optgroup: 'strings' }, { type: 'not_contains', optgroup: 'strings' }, { type: 'ends_with', optgroup: 'strings' }, { type: 'not_ends_with', optgroup: 'strings' }, { type: 'is_empty' }, { type: 'is_not_empty' }, { type: 'is_null' }, { type: 'is_not_null' } ], filters: [] }; $b.queryBuilder(options); ``` -------------------------------- ### QueryBuilder beforeReset Event Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/events.md Listen for the `beforeReset` event, which fires before the `reset()` method is called. This event is preventable using `e.preventDefault()`, allowing you to prompt the user for confirmation before resetting. ```javascript $('#builder').queryBuilder('on', 'beforeReset', function(e) { if (!confirm('Reset all rules?')) { e.preventDefault(); } }); ``` -------------------------------- ### Modify QueryBuilder Options at Runtime Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/configuration.md Use the `setOptions()` method to change configuration settings after the QueryBuilder has been initialized. This is useful for dynamically adjusting behavior like allowing empty root groups or setting a default condition. ```javascript $('#builder').queryBuilder('setOptions', { allow_empty: true, default_condition: 'OR' }); ``` -------------------------------- ### setOptions(options) Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/api-reference.md Modifies the builder configuration at runtime. Only specific modifiable options can be changed. The `options` parameter is a configuration object with option keys and values. ```APIDOC ## setOptions(options) ### Description Modifies the builder configuration at runtime. Only options listed in `QueryBuilder.modifiable_options` can be changed. ### Method `setOptions(options)` ### Parameters #### Request Body - **options** (object) - Required - Configuration object with option keys and values ### Modifiable Options `display_errors`, `allow_groups`, `allow_empty`, `default_condition`, `default_filter` ### Returns `undefined` ### Example ```javascript $("#builder").queryBuilder("setOptions", { allow_empty: true, default_condition: 'OR' }); ``` ``` -------------------------------- ### Data Export and Import Methods Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/README.md Methods for exporting rules to different formats like SQL and MongoDB, and importing them back. ```APIDOC ## getRulesAsSQL() ### Description Exports the current rules in the QueryBuilder into a SQL query string. Requires the 'sql-support' plugin. ### Method GET (conceptual) ### Endpoint N/A (Method call) ### Parameters None ### Response #### Success Response - **sql** (string) - The generated SQL query string. ### Response Example ```sql SELECT * FROM my_table WHERE name = 'John Doe' AND age > 30 ``` ``` ```APIDOC ## sqlToRules(sql_query) ### Description Imports rules from a SQL query string into the QueryBuilder. Requires the 'sql-support' plugin. ### Method POST (conceptual) ### Endpoint N/A (Method call) ### Parameters - **sql_query** (string) - Required - The SQL query string to parse. ### Response #### Success Response - **rules** (object) - The parsed rules object. ### Response Example ```json { "condition": "AND", "rules": [ { "id": "name", "field": "name", "type": "string", "input": "text", "operator": "equal", "value": "John Doe" } ] } ``` ``` ```APIDOC ## getRulesAsMongoDBQuery() ### Description Exports the current rules in the QueryBuilder into a MongoDB query object. Requires the 'mongodb-support' plugin. ### Method GET (conceptual) ### Endpoint N/A (Method call) ### Parameters None ### Response #### Success Response - **mongo_query** (object) - The generated MongoDB query object. ### Response Example ```json { "name": "John Doe", "age": { "$gt": 30 } } ``` ``` -------------------------------- ### Register a QueryBuilder Plugin Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/plugins.md Register a new plugin with QueryBuilder using its name, initialization function, and default options. ```javascript QueryBuilder.define(name, initFunction, defaultOptions); ``` -------------------------------- ### Static Methods Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/DOCUMENTATION_MANIFEST.txt Offers 3 static methods available on the QueryBuilder class itself, typically used for utility functions or global configurations. ```APIDOC ## Static Methods ### Description Offers 3 static methods available on the QueryBuilder class itself, typically used for utility functions or global configurations. ### Method JavaScript (jQuery plugin static methods) ### Endpoint N/A (jQuery plugin static methods) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript var defaults = QueryBuilder.defaults; ``` ### Response #### Success Response (200) Depends on the static method called. #### Response Example Depends on the static method called. ``` -------------------------------- ### Complete QueryBuilder Configuration Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/configuration.md This snippet shows a comprehensive configuration for the jQuery QueryBuilder, including data filters, behavior settings, UI customizations, localization, plugin integration, and initial query rules. Use this as a template for setting up the builder with specific data structures and user interface preferences. ```javascript $("#builder").queryBuilder({ // Data configuration filters: [ { id: 'name', label: 'Name', type: 'string', input: 'text', validation: { min: 1, max: 100 } }, { id: 'age', label: 'Age', type: 'integer', input: 'number', operators: ['equal', 'less', 'greater', 'between'], validation: { min: 0, max: 150 } }, { id: 'status', label: 'Status', type: 'string', input: 'select', values: { 'active': 'Active', 'inactive': 'Inactive' } } ], // Behavior configuration allow_empty: false, allow_groups: true, default_condition: 'AND', display_errors: true, // UI configuration sort_filters: true, display_empty_filter: true, select_placeholder: '-- Choose --', icons: { add_group: 'bi-plus-circle-fill', add_rule: 'bi-plus-lg', remove_group: 'bi-x-lg', remove_rule: 'bi-x-lg', error: 'bi-exclamation-triangle' }, // Localization lang_code: 'en', lang: { operators: { equal: 'Equals' } }, // Plugins plugins: { 'sql-support': {}, 'bt-tooltip-errors': {} }, // Initial data rules: { condition: 'AND', rules: [ { id: 'name', operator: 'contains', value: 'John' } ] } }); ``` -------------------------------- ### Export QueryBuilder Rules Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/INDEX.md Demonstrates how to export current query builder rules in various formats like JSON, SQL, and MongoDB query. Flags can be included in the JSON export. ```javascript // Get as JSON var rules = $('#builder').queryBuilder('getRules'); // With flags var rulesWithFlags = $('#builder').queryBuilder('getRules', { get_flags: 'all' }); // As SQL (requires sql-support plugin) var sql = $('#builder').queryBuilder('getRulesAsSQL'); // As MongoDB query (requires mongodb-support plugin) var mongoQuery = $('#builder').queryBuilder('getRulesAsMongoDBQuery'); ``` -------------------------------- ### bt-tooltip-errors Plugin Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/plugins.md Implements Bootstrap tooltips to display validation errors, offering a cleaner alternative to inline error containers. ```APIDOC ## bt-tooltip-errors Plugin ### Description Displays validation errors as Bootstrap tooltips instead of inline error containers for a cleaner error display. ### Configuration Options None ### Requirements Bootstrap 5 and Popper.js ### Behavior - Shows tooltip on invalid rule/group - Tooltip appears on hover - Contains error message and icon ``` -------------------------------- ### Configure Select Input Filter with Optgroups Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/INDEX.md Define a string filter with a select input, organizing options into optgroups. Useful for categorizing select options. ```javascript { id: 'product', type: 'string', input: 'select', values: [ {value: 'iphone', label: 'iPhone', optgroup: 'Apple'}, {value: 'ipad', label: 'iPad', optgroup: 'Apple'} ] } ``` -------------------------------- ### Model Methods Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/types.md Provides methods for interacting with the Model, such as triggering events, attaching, detaching, and listening to events. ```APIDOC ## Model Methods ### Description Methods for interacting with the Model object, including event handling and manipulation. ### Methods - **`model.trigger(type, ...args)`** - Description: Triggers a specified event with given arguments. - Returns: An instance of `$.Event`. - **`model.on(type, callback)`** - Description: Attaches a listener callback to a specific event type. - Returns: The `Model` instance for chaining. - **`model.off(type, callback)`** - Description: Removes a listener callback for a specific event type. - Returns: The `Model` instance for chaining. - **`model.once(type, callback)`** - Description: Attaches a one-time listener callback that will be removed after being triggered. - Returns: The `Model` instance for chaining. ``` -------------------------------- ### Convert Rules to SQL for Backend Execution Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/advanced-usage.md Convert query builder rules into a SQL string using `getRulesAsSQL`. This SQL can then be sent to the backend via a POST request to execute the query and retrieve results. ```javascript // Convert to SQL var rules = $('#builder').queryBuilder('getRules'); if (rules.valid) { var sql = $('#builder').queryBuilder('getRulesAsSQL'); // Execute query on backend $.post('/api/query', { sql: sql }, function(results) { displayResults(results); }); } ``` -------------------------------- ### Node (Abstract) Methods Source: https://github.com/mistic100/jquery-querybuilder/blob/dev/_autodocs/types.md Provides methods for interacting with nodes in the query tree, including checking if a node is the root, if it contains another node, its position, and for dropping (removing) the node. ```javascript node.isRoot() → boolean // check if node is root group node.contains(otherNode) → boolean // check if node contains another node.getPos() → number // position in parent's rules array node.getNodePos() → number // position including parent nesting node.drop() → undefined // remove from tree ```