<commit_before>#backbone-forms

A flexible, customisable form framework for Backbone.JS applications. Includes validation, nested models and custom editors.

Simply define a schema on your models and the forms will be auto-generated for you:

    var User = Backbone.Model.extend({
        schema: {
            email:      { dataType: 'email', validators: ['required', 'email'] },
            start:      { type: 'DateTime' },
            contact:    { type: 'Object', subSchema: {
                            name: { validators: ['required'] },
                            phone: {}
                        }}
            address:    { type: 'NestedModel', model: Address },
            notes:      { type: 'List', help: 'Helpful notes' }
        }
    });
    
The schema above will automatically create a form similar to this:

![Example form](http://i56.tinypic.com/a3zfyt.png)



<a name="top"/>
##Table of Contents:
- [Installation](#installation)
- [Usage](#usage)
- [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)



<a name="installation"/>
#Installation

Dependencies:
- [Backbone 0.9.1](http://documentcloud.github.com/backbone/)


Include backbone-forms.js and backbone-forms.css:

    <link href="backbone-forms/backbone-forms.css" rel="stylesheet" type="text/css"/> 
    <script src="backbone-forms/src/backbone-forms.js"></script>

Optionally, you can include the extra editors, for example those that require jQuery UI:

    <script src="backbone-forms/src/jquery-ui-editors.js"></script>
    
To use a custom template pack, e.g. Bootstrap, include the relevant file after backbone-forms.js:

    <script src="backbone-forms/src/templates/bootstrap.js"></script>

If you use BackboneJS with node.js, you can just `require('backbone-forms');` in your index file.

[Back to top](#top)



<a name="usage"/>
#Usage

Define a 'schema' attribute on your Backbone models. The schema keys should match the attributes that get set on the model. Note that `type` defaults to `Text`.
See [schema definition](#schema-definition) for more information.

    var User = Backbone.Model.extend({
        schema: {
            email:      { dataType: 'email', validators: ['required', validateEmail] },
            start:      { type: 'DateTime' },
            contact:    { type: 'Object', subSchema: {
                            name: {},
                            phone: {}
                        }}
            address:    { type: 'NestedModel', model: Address },
            notes:      { type: 'List' }
        }
    });

Create the form in your Views:
    
    var formView = Backbone.View.extend({
        render: function() {
            var form = new Backbone.Form({
                model: users.get(userId)
            }).render();
            
            $(this.el).append(form.el);
            
            return this;
        }
    });


Once the user is done with the form, call 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 `setValue`:

    model.bind('change:name', function(model, name) {
        form.fields.name.setValue(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: { id: 123, name: '<NAME>', password: '<PASSWORD>' }, //Data to populate the form with
        schema: {
            id:         { type: 'Number' },
            name:       {},
            password:   { type: '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)



<a name="schema-definition"/>
#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)

In addition there is a separate file with editors that depend on jQuery UI:

- [Date](#editor-date)
- [DateTime](#editor-datetime)
- [List](#editor-list) (Editable and sortable. Can use any of the other editors for each item)



##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, e.g. for a custom editor: `{ type: MyEditor }`
- If not defined, defaults to 'Text'

**`title`**

- Defines the text that appears in a form field's &lt;label&gt;
- If not defined, defaults to a formatted version of the camelCased field key. E.g. `firstName` becomes `First Name`. This behaviour can be changed by assigning your own function to Backbone.Form.helpers.keyToTitle.

**`validators`**

- A list of validators. See [Validation](#validation) for more information

**`help`**

- Help text to add next to the editor.

**`editorClass`**

- String of CSS class name(s) to add to the editor

**`editorAttrs`**

- A map of attributes to add to the editor, e.g. `{ maxlength: 30, title: 'Tooltip help' }`

**`fieldClass`**

- String of CSS class name(s) to add to the field

**`fieldAttrs`**

- A map of attributes to add to the field, e.g. `{ style: 'background: red', title: 'Tooltip help' }`



<a name="editor-text"/>
##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.


<a name="editor-select"/>
##Select
<commit_msg>Docs for field template option<commit_after>#backbone-forms

A flexible, customisable form framework for Backbone.JS applications. Includes validation, nested models and custom editors.

Simply define a schema on your models and the forms will be auto-generated for you:

    var User = Backbone.Model.extend({
        schema: {
            email:      { dataType: 'email', validators: ['required', 'email'] },
            start:      { type: 'DateTime' },
            contact:    { type: 'Object', subSchema: {
                            name: { validators: ['required'] },
                            phone: {}
                        }}
            address:    { type: 'NestedModel', model: Address },
            notes:      { type: 'List', help: 'Helpful notes' }
        }
    });
    
The schema above will automatically create a form similar to this:

![Example form](http://i56.tinypic.com/a3zfyt.png)



<a name="top"/>
##Table of Contents:
- [Installation](#installation)
- [Usage](#usage)
- [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)



<a name="installation"/>
#Installation

Dependencies:
- [Backbone 0.9.1](http://documentcloud.github.com/backbone/)


Include backbone-forms.js and backbone-forms.css:

    <link href="backbone-forms/backbone-forms.css" rel="stylesheet" type="text/css"/> 
    <script src="backbone-forms/src/backbone-forms.js"></script>

Optionally, you can include the extra editors, for example those that require jQuery UI:

    <script src="backbone-forms/src/jquery-ui-editors.js"></script>
    
To use a custom template pack, e.g. Bootstrap, include the relevant file after backbone-forms.js:

    <script src="backbone-forms/src/templates/bootstrap.js"></script>

If you use BackboneJS with node.js, you can just `require('backbone-forms');` in your index file.

[Back to top](#top)



<a name="usage"/>
#Usage

Define a 'schema' attribute on your Backbone models. The schema keys should match the attributes that get set on the model. Note that `type` defaults to `Text`.
See [schema definition](#schema-definition) for more information.

    var User = Backbone.Model.extend({
        schema: {
            email:      { dataType: 'email', validators: ['required', validateEmail] },
            start:      { type: 'DateTime' },
            contact:    { type: 'Object', subSchema: {
                            name: {},
                            phone: {}
                        }}
            address:    { type: 'NestedModel', model: Address },
            notes:      { type: 'List' }
        }
    });

Create the form in your Views:
    
    var formView = Backbone.View.extend({
        render: function() {
            var form = new Backbone.Form({
                model: users.get(userId)
            }).render();
            
            $(this.el).append(form.el);
            
            return this;
        }
    });


Once the user is done with the form, call 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 `setValue`:

    model.bind('change:name', function(model, name) {
        form.fields.name.setValue(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: { id: 123, name: '<NAME>', password: '<PASSWORD>' }, //Data to populate the form with
        schema: {
            id:         { type: 'Number' },
            name:       {},
            password:   { type: '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)



<a name="schema-definition"/>
#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)

In addition there is a separate file with editors that depend on jQuery UI:

- [Date](#editor-date)
- [DateTime](#editor-datetime)
- [List](#editor-list) (Editable and sortable. Can use any of the other editors for each item)



##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, e.g. for a custom editor: `{ type: MyEditor }`
- If not defined, defaults to 'Text'

**`title`**

- Defines the text that appears in a form field's &lt;label&gt;
- If not defined, defaults to a formatted version of the camelCased field key. E.g. `firstName` becomes `<NAME>`. This behaviour can be changed by assigning your own function to Backbone.Form.helpers.keyToTitle.

**`validators`**

- A list of validators. See [Validation](#validation) for more information

**`help`**

- Help text to add next to the editor.

**`editorClass`**

- String of CSS class name(s) to add to the editor

**`editorAttrs`**

- A map of attributes to add to the editor, e.g. `{ maxlength: 30, title: 'Tooltip help' }`

**`fieldClass`**

- String of CSS class name(s) to add to the field

**`fieldAttrs`**

- A map of attributes to add to the field, e.g. `{ style: 'background: red', title: 'Tooltip help' }`

**`template`**

- Name of the template to use for this field. See [Customising templates](#customising-templates) for more information.



<a name="editor-text"/>
##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.


<a name="editor-select"/>
##Select

{'fraction_non_alphanumeric': 0.12716637781629117, 'fraction_numerical': 0.0017331022530329288, 'mean_word_length': 2.8956399437412097, 'pattern_counts': {'":': 0, '<': 34, '<?xml version=': 0, '>': 34, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4832408', 'n_tokens_mistral': 4101, 'n_tokens_neox': 3909, 'n_words': 1457}