#backbone-forms A flexible, customisable form framework for Backbone.JS applications. - Simple schema definition to auto-generate forms - Validation - Nested forms - Advanced and custom editors (e.g. NestedModel, List, Date, DateTime) - Custom HTML templates ###Example var User = Backbone.Model.extend({ schema: { title: { type: 'Select', options: ['Mr', 'Mrs', 'Ms'] }, name: 'Text', email: { validators: ['required', 'email'] }, birthday: 'Date', password: 'Password', address: { type: 'NestedModel', model: Address }, notes: { type: 'List', listType: 'Text' } } }); var user = new User(); var form = new Backbone.Form({ model: user }).render(); $('body').append(form.el); ###Live editable demos - [User form](http://jsfiddle.net/evilcelery/VkUFu/) - [Form with Bootstrap templates and an Object list](http://jsfiddle.net/evilcelery/4XZMb/) - [Update form elements based on user input](http://jsfiddle.net/evilcelery/c5QHr/) ##Guide ###Table of Contents: - [Installation](#installation) - [Usage](#usage) - [Backbone.Form](#form) - [Schema Definition](#schema-definition) - [Text](#editor-text) - [Checkboxes](#editor-checkboxes) - [Select](#editor-select) - [Radio](#editor-radio) - [Object](#editor-object) - [NestedModel](#editor-nestedmodel) - [Date](#editor-date) - [DateTime](#editor-datetime) - [List](#editor-list) - [Validation](#validation) - [Customising templates](#customising-templates) - [More](#more) - [Editors without forms](#editors-without-forms) - [Using nested fields](#nested-fields) - [Custom editors](#custom-editors) - [Help](#help) - [Changelog](#changelog) ##Installation Dependencies: - [Backbone 0.9.2](http://documentcloud.github.com/backbone/) Include backbone-forms.js and backbone-forms.css: Optionally, you can include the extra editors, for example the List editor: To use a custom template pack, e.g. Bootstrap, include the relevants file after backbone-forms.js. You can remove `templates/default.css` and replace it with `templates/bootstrap.css`. If you use Backbone with node.js, you can just `require('backbone-forms');` in your index file. Note there is also a distribution file for RequireJS / AMD. [Back to top](#top) ##Usage Define a `schema` attribute on your Backbone models. The schema keys should match the attributes that get set on the model. `type` defaults to `Text`. When you don't need to specify any options you can use the shorthand by passing the editor name as a string. See [schema definition](#schema-definition) for more information. var User = Backbone.Model.extend({ schema: { title: { type: 'Select', options: ['Mr', 'Mrs', 'Ms'] }, name: 'Text', email: { validators: ['required', 'email'] }, birthday: 'Date', password: 'Password', address: { type: 'NestedModel', model: Address }, notes: { type: 'List', listType: 'Text' } } }); var user = new User(); var form = new Backbone.Form({ model: user }).render(); $('body').append(form.el); Once the user is done with the form, call `form.commit()` to apply the updated values to the model. If there are validation errors they will be returned. See [validation](#validation) for more information. var errors = form.commit(); To update a field after the form has been rendered, use `form.setValue`: model.on('change:name', function(model, name) { form.setValue({ name: name }); }); ###Usage without models You can create a form without tying it to a model. For example, to create a form for a simple object of data: var form = new Backbone.Form({ //Data to populate the form with data: { id: 123, name: 'Rod Kimble', password: 'cool beans' }, //Schema schema: { id: 'Number', name: 'Text', password: 'Password' } }).render(); Then instead of `form.commit()`, do: var data = form.getValue(); //Returns object with new form values ###Initial data If a form has a model attached to it, the initial values are taken from the model's defaults. Otherwise, you may pass default values using the `schema.data`. [Back to top](#top) ##Backbone.Form ###Options - **`model`** The model to tie the form to. Calling `form.commit()` will update the model with new values. - **`data`** If not using the `model` option, pass a native object through the `data` option. Then use `form.getValue()` to get the new values. - **`schema`** The schema to use to create the form. Pass it in if you don't want to store the schema on the model, or to override the model schema. - **`fieldsets`** An array of fieldsets descriptions. A fieldset is either a list of field names, or an object with `legend` and `fields` attributes. The `legend` will be inserted at the top of the fieldset inside a `` tag; the list of fields will be treated as `fields` is below. `fieldsets` takes priority over `fields`. - **`fields`** An array of field names (keys). Only the fields defined here will be added to the form. You can also use this to re-order the fields. - **`idPrefix`** A string that will be prefixed to the form DOM element IDs. Useful if you will have multiple forms on the same page. E.g. `idPrefix: 'user-'` will result in IDs like 'user-name', 'user-email', etc. If not defined, the model's CID will be used as a prefix to avoid conflicts when there are multiple instances of the form on the page. To override this behaviour, pass a null value to `idPrefix`. - **`template`** The template name to use for generating the form. E.g.: Backbone.Form.setTemplates({ customForm: '
{{fieldsets}}
' }); var form = new Backbone.Form({ model: user, template: 'customForm' }); ###Events `Backbone.Form` fires the following events: - **`change`** This event is triggered whenever something happens that affects the result of `form.getValue()`. - **`focus`** This event is triggered whenever this form gains focus, i.e. when the input of an editor within this form becomes the `document.activeElement`. - **`blur`** This event is triggered whenever this form loses focus, i.e. when the input of an editor within this form stops being the `document.activeElement`. - **`:`** Events fired by editors within this form will bubble up and be fired as `:`. form.on('title:change', function(form, titleEditor) { console.log('Title changed to "' + titleEditor.getValue() + '".'); }); [Back to top](#top)
##Schema definition The schema defined on your model can be the schema object itself, or a function that returns a schema object. This can be useful if you're referencing variables that haven't been initialized yet. The following default editors are included: - [Text](#editor-text) - Number - Password - TextArea - Checkbox - [Checkboxes](#editor-checkboxes) - Hidden - [Select](#editor-select) - [Radio](#editor-radio) - [Object](#editor-object) - [NestedModel](#editor-nestedmodel) - [Date](#editor-date) - [DateTime](#editor-datetime) - [List](#editor-list) An editable list of items (included in a separate file: `distribution/editors/list.min.js`) The old jQuery editors are still included but may be moved to another repository: - jqueryui.List - jqueryui.Date (uses the jQuery UI popup datepicker) - jqueryui.DateTime ###Main attributes For each field definition in the schema you can use the following optional attributes: - **`type`** The editor to use in the field. Can be a string for any editor that has been added to `Backbone.Form.editors`, such as the built-in editors (e.g. `{ type: 'TextArea' }`), or can be a constructor function for a custom editor (e.g. : `{ type: MyEditor }`). If not defined, defaults to 'Text'. - **`title`** Defines the text that appears in a form field's ` ##Text Creates a normal text input. - **`dataType`** Changes the `type="text"` attribute. Used for HTML5 form inputs such as `url`, `tel`, `email`. When viewing on a mobile device e.g. iOS, this will change the type of keyboard that is opened. For example, `tel` opens a numeric keypad. ##Select Creates and populates a ``. Can be either: - String of HTML ` ##Radio Creates and populates a list of radio inputs. Behaves the same way and has the same options as a `Select`. ##Checkboxes Creates and populates a list of checkbox inputs. Behaves the same way and has the same options as a `Select`. To set defaults for this editor, use an array of values. ##Object The Object editor creates an embedded child form representing a Javascript object. ###Attributes - **`subSchema`** A schema object which defines the field schema for each attribute in the object ###Events - **`:`** Events fired by editors within this Object editor will bubble up and be fired as `:`. ####Examples var schema = { address: { type: 'Object', subSchema: { street: {}, zip: { type: 'Number' }, country: { 'Select', options: countries } }} }; addressEditor.on('zip:change', function(addressEditor, zipEditor) { console.log('Zip changed to "' + zipEditor.getValue() + '".'); }); ##NestedModel Used to embed models within models. Similar to the Object editor, but adds validation of the child form (if it is defined on the model), and keeps your schema cleaner. ###Attributes - **`model`** A reference to the constructor function for your nested model. The referenced model must have it's own `schema` attribute ###Events - **`:`** Events fired by editors within this NestedModel editor will bubble up and be fired as `:`. ####Examples var schema = { address: { type: 'NestedModel', model: Address } }; addressEditor.on('zip:change', function(addressEditor, zipEditor) { console.log('Zip changed to "' + zipEditor.getValue() + '".'); }); ##Date Creates ``s for time (hours and minutes). - **`minsInterval`** Optional. Controls the numbers in the minutes dropdown. Defaults to 15, so it is populated with 0, 15, 30, and 45 minutes. ##List Creates a list of items that can be added, removed and edited. Used to manage arrays of data. This is a special editor which is in **a separate file and must be included**: