Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 685 lines (430 sloc) 21.721 kB
f2ce846 @powmedia Update README.md
authored
1 #backbone-forms
646f014 @powmedia first commit
authored
2
fe19789 @powmedia Update README.md
authored
3 A flexible, customisable form framework for Backbone.JS applications. Includes validation, nested models and custom editors.
646f014 @powmedia first commit
authored
4
fe19789 @powmedia Update README.md
authored
5 Simply define a schema on your models and the forms will be auto-generated for you:
eea1606 @powmedia Docs
authored
6
fe19789 @powmedia Update README.md
authored
7 var User = Backbone.Model.extend({
8 schema: {
103860f @powmedia Update README.md
authored
9 email: { dataType: 'email', validators: ['required', 'email'] },
fe19789 @powmedia Update README.md
authored
10 start: { type: 'DateTime' },
11 contact: { type: 'Object', subSchema: {
103860f @powmedia Update README.md
authored
12 name: { validators: ['required'] },
fe19789 @powmedia Update README.md
authored
13 phone: {}
14 }}
15 address: { type: 'NestedModel', model: Address },
103860f @powmedia Update README.md
authored
16 notes: { type: 'List', help: 'Helpful notes' }
fe19789 @powmedia Update README.md
authored
17 }
18 });
19
20 The schema above will automatically create a form similar to this:
eea1606 @powmedia Docs
authored
21
fe19789 @powmedia Update README.md
authored
22 ![Example form](http://i56.tinypic.com/a3zfyt.png)
eea1606 @powmedia Docs
authored
23
24
25
35950ec @powmedia Update README.md
authored
26 <a name="top"/>
fe19789 @powmedia Update README.md
authored
27 ##Table of Contents:
28 - [Installation](#installation)
29 - [Usage](#usage)
30 - [Schema Definition](#schema-definition)
31 - [Text](#editor-text)
32 - [Checkboxes](#editor-checkboxes)
33 - [Select](#editor-select)
34 - [Radio](#editor-radio)
35 - [Object](#editor-object)
36 - [NestedModel](#editor-nestedmodel)
37 - [Date](#editor-date)
38 - [DateTime](#editor-datetime)
39 - [List](#editor-list)
3900a2b @powmedia Templating docs
authored
40 - [Validation](#validation)
41 - [Customising templates](#customising-templates)
35950ec @powmedia Update README.md
authored
42 - [More](#more)
43 - [Editors without forms](#editors-without-forms)
44 - [Using nested fields](#nested-fields)
45 - [Custom editors](#custom-editors)
0a9f430 @powmedia Update README.md
authored
46 - [Help](#help)
fe19789 @powmedia Update README.md
authored
47
48
49
50 <a name="installation"/>
f2ce846 @powmedia Update README.md
authored
51 #Installation
eea1606 @powmedia Docs
authored
52
1e17bab @powmedia Docs
authored
53 Dependencies:
54 - [Backbone 0.9.1](http://documentcloud.github.com/backbone/)
55
eea1606 @powmedia Docs
authored
56
0b49de4 @powmedia Add CSS
authored
57 Include backbone-forms.js and backbone-forms.css:
eea1606 @powmedia Docs
authored
58
0b49de4 @powmedia Add CSS
authored
59 <link href="backbone-forms/backbone-forms.css" rel="stylesheet" type="text/css"/>
eea1606 @powmedia Docs
authored
60 <script src="backbone-forms/src/backbone-forms.js"></script>
61
62 Optionally, you can include the extra editors, for example those that require jQuery UI:
646f014 @powmedia first commit
authored
63
eea1606 @powmedia Docs
authored
64 <script src="backbone-forms/src/jquery-ui-editors.js"></script>
1e17bab @powmedia Docs
authored
65
66 To use a custom template pack, e.g. Bootstrap, include the relevant file after backbone-forms.js:
67
68 <script src="backbone-forms/src/templates/bootstrap.js"></script>
ce1689f @vkareh Make compatible with node.js as a module.
vkareh authored
69
70 If you use BackboneJS with node.js, you can just `require('backbone-forms');` in your index file.
35950ec @powmedia Update README.md
authored
71
72 [Back to top](#top)
73
646f014 @powmedia first commit
authored
74
088e9f9 @powmedia Docs
authored
75
fe19789 @powmedia Update README.md
authored
76 <a name="usage"/>
77 #Usage
088e9f9 @powmedia Docs
authored
78
37872a1 @powmedia Docs
authored
79 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`.
10627d4 @powmedia Update README.md
authored
80 See [schema definition](#schema-definition) for more information.
646f014 @powmedia first commit
authored
81
82 var User = Backbone.Model.extend({
83 schema: {
f25c786 @powmedia Add email validation example
authored
84 email: { dataType: 'email', validators: ['required', validateEmail] },
088e9f9 @powmedia Docs
authored
85 start: { type: 'DateTime' },
86 contact: { type: 'Object', subSchema: {
87 name: {},
88 phone: {}
89 }}
37872a1 @powmedia Docs
authored
90 address: { type: 'NestedModel', model: Address },
088e9f9 @powmedia Docs
authored
91 notes: { type: 'List' }
646f014 @powmedia first commit
authored
92 }
93 });
94
95 Create the form in your Views:
088e9f9 @powmedia Docs
authored
96
646f014 @powmedia first commit
authored
97 var formView = Backbone.View.extend({
98 render: function() {
eea1606 @powmedia Docs
authored
99 var form = new Backbone.Form({
088e9f9 @powmedia Docs
authored
100 model: users.get(userId)
646f014 @powmedia first commit
authored
101 }).render();
102
103 $(this.el).append(form.el);
104
105 return this;
106 }
107 });
108
eea1606 @powmedia Docs
authored
109
10627d4 @powmedia Update README.md
authored
110 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.
646f014 @powmedia first commit
authored
111
112 var errors = form.commit();
113
01b6fe8 @powmedia Docs
authored
114 To update a field after the form has been rendered, use `setValue`:
115
116 model.bind('change:name', function(model, name) {
117 form.fields.name.setValue(name);
118 });
4619643 @powmedia Docs
authored
119
646f014 @powmedia first commit
authored
120
f2ce846 @powmedia Update README.md
authored
121 ##Usage without models
eea1606 @powmedia Docs
authored
122
123 You can create a form without tying it to a model. For example, to create a form for a simple object of data:
124
125 var form = new Backbone.Form({
126 data: { id: 123, name: 'Rod Kimble', password: 'cool beans' }, //Data to populate the form with
127 schema: {
37872a1 @powmedia Docs
authored
128 id: { type: 'Number' },
129 name: {},
130 password: { type: 'Password' }
eea1606 @powmedia Docs
authored
131 }
132 }).render();
133
134 Then instead of form.commit(), do:
135
136 var data = form.getValue(); //Returns object with new form values
137
138
fe19789 @powmedia Update README.md
authored
139 ##Initial data
140 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`.
141
35950ec @powmedia Update README.md
authored
142 [Back to top](#top)
143
144
fe19789 @powmedia Update README.md
authored
145
146 <a name="schema-definition"/>
f2ce846 @powmedia Update README.md
authored
147 #Schema definition
646f014 @powmedia first commit
authored
148
72ce855 @powmedia Allow model.schema to be a function that returns the schema object
authored
149 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.
150
fe19789 @powmedia Update README.md
authored
151 The following default editors are included:
152
153 - [Text](#editor-text)
154 - Number
155 - Password
156 - TextArea
157 - Checkbox
158 - [Checkboxes](#editor-checkboxes)
159 - Hidden
160 - [Select](#editor-select)
161 - [Radio](#editor-radio)
162 - [Object](#editor-object)
163 - [NestedModel](#editor-nestedmodel)
164
165 In addition there is a separate file with editors that depend on jQuery UI:
166
167 - [Date](#editor-date)
168 - [DateTime](#editor-datetime)
169 - [List](#editor-list) (Editable and sortable. Can use any of the other editors for each item)
170
171
172
f2ce846 @powmedia Update README.md
authored
173 ##Main attributes
646f014 @powmedia first commit
authored
174
eea1606 @powmedia Docs
authored
175 For each field definition in the schema you can use the following optional attributes:
646f014 @powmedia first commit
authored
176
eea1606 @powmedia Docs
authored
177 **`type`**
646f014 @powmedia first commit
authored
178
eea1606 @powmedia Docs
authored
179 - The editor to use in the field
37872a1 @powmedia Docs
authored
180 - 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' }`
eea1606 @powmedia Docs
authored
181 - Or can be a constructor function, e.g. for a custom editor: `{ type: MyEditor }`
d3f6be7 @powmedia Rename TextField to Text
authored
182 - If not defined, defaults to 'Text'
646f014 @powmedia first commit
authored
183
eea1606 @powmedia Docs
authored
184 **`title`**
646f014 @powmedia first commit
authored
185
37872a1 @powmedia Docs
authored
186 - Defines the text that appears in a form field's &lt;label&gt;
187 - 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.
646f014 @powmedia first commit
authored
188
9bc1634 @mjtamlyn Validation.
mjtamlyn authored
189 **`validators`**
190
fe19789 @powmedia Update README.md
authored
191 - A list of validators. See [Validation](#validation) for more information
9bc1634 @mjtamlyn Validation.
mjtamlyn authored
192
103860f @powmedia Update README.md
authored
193 **`help`**
194
195 - Help text to add next to the editor.
196
922952f @powmedia Add fieldClass, fieldAttrs, editorClass, editorAttrs schema options
authored
197 **`editorClass`**
198
199 - String of CSS class name(s) to add to the editor
200
201 **`editorAttrs`**
202
203 - A map of attributes to add to the editor, e.g. `{ maxlength: 30, title: 'Tooltip help' }`
204
205 **`fieldClass`**
354e6b2 @powmedia Add 'attrs' and 'className' field schema attributes
authored
206
207 - String of CSS class name(s) to add to the field
208
922952f @powmedia Add fieldClass, fieldAttrs, editorClass, editorAttrs schema options
authored
209 **`fieldAttrs`**
354e6b2 @powmedia Add 'attrs' and 'className' field schema attributes
authored
210
211 - A map of attributes to add to the field, e.g. `{ style: 'background: red', title: 'Tooltip help' }`
212
5f1ee18 @powmedia Docs for field template option
authored
213 **`template`**
214
215 - Name of the template to use for this field. See [Customising templates](#customising-templates) for more information.
216
646f014 @powmedia first commit
authored
217
218
f2fab62 @powmedia Links in readme
authored
219 <a name="editor-text"/>
220 ##Text
809b7ec @powmedia Add 'dataType' option to Text schema. Closes #11
authored
221
222 Creates a normal text input.
223
224 **`dataType`**
225
10627d4 @powmedia Update README.md
authored
226 - 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.
809b7ec @powmedia Add 'dataType' option to Text schema. Closes #11
authored
227
228
f2fab62 @powmedia Links in readme
authored
229 <a name="editor-select"/>
f2ce846 @powmedia Update README.md
authored
230 ##Select
eea1606 @powmedia Docs
authored
231
3708193 @powmedia Fix readme chars
authored
232 Creates and populates a &lt;select&gt; element.
eea1606 @powmedia Docs
authored
233
234 **`options`**
235
3708193 @powmedia Fix readme chars
authored
236 - Options to populate the &lt;select&gt;
eea1606 @powmedia Docs
authored
237 - Can be either:
3708193 @powmedia Fix readme chars
authored
238 - String of HTML &lt;option&gt;`s
37872a1 @powmedia Docs
authored
239 - Array of strings/numbers
eea1606 @powmedia Docs
authored
240 - Array of objects in the form `{ val: 123, label: 'Text' }`
241 - A Backbone collection
242 - A function that calls back with one of the above
243
244 Examples:
245
246 var schema = {
922952f @powmedia Add fieldClass, fieldAttrs, editorClass, editorAttrs schema options
authored
247 country: { type: 'Select', options: new CountryCollection() }
eea1606 @powmedia Docs
authored
248 };
249
250 var schema = {
922952f @powmedia Add fieldClass, fieldAttrs, editorClass, editorAttrs schema options
authored
251 users: { type: 'Select', options: function(callback) {
eea1606 @powmedia Docs
authored
252 users = db.getUsers();
253
254 callback(users);
255 }}
256 }
257
258 **Backbone collection notes**
3708193 @powmedia Fix readme chars
authored
259
260 If using a Backbone collection as the `option` attribute, models in the collection must implement a `toString()` method. This populates the label of the &lt;option&gt;. The ID of the model populates the `value` attribute.
eea1606 @powmedia Docs
authored
261
262 If there are no models in the collection, it will be `fetch()`ed.
263
f2fab62 @powmedia Links in readme
authored
264
265 <a name="editor-radio"/>
f2ce846 @powmedia Update README.md
authored
266 ##Radio
aca597f @mjtamlyn Add basic documentation of the Radio editor.
mjtamlyn authored
267
268 Creates and populates a list of radio inputs. Behaves the same way and has the same options as a `Select`.
eea1606 @powmedia Docs
authored
269
f2fab62 @powmedia Links in readme
authored
270
271 <a name="editor-checkboxes"/>
f2ce846 @powmedia Update README.md
authored
272 ##Checkboxes
6d32f8d @vkareh Add Checkboxes editor.
vkareh authored
273
274 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.
275
f2fab62 @powmedia Links in readme
authored
276
277 <a name="editor-object"/>
f2ce846 @powmedia Update README.md
authored
278 ##Object
eea1606 @powmedia Docs
authored
279
280 The Object editor creates an embedded child form representing a Javascript object.
281
282 **`subSchema`**
283
284 - A schema object which defines the field schema for each attribute in the object
285
286 Examples:
287
288 var schema = {
289 address: { type: 'Object', subSchema: {
290 street: {},
291 zip: { type: 'Number' },
292 country: { 'Select', options: countries }
293 }}
294 };
295
296
f2fab62 @powmedia Links in readme
authored
297 <a name="editor-nestedmodel"/>
f2ce846 @powmedia Update README.md
authored
298 ##NestedModel
eea1606 @powmedia Docs
authored
299
37872a1 @powmedia Docs
authored
300 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.
646f014 @powmedia first commit
authored
301
eea1606 @powmedia Docs
authored
302 **`model`**
646f014 @powmedia first commit
authored
303
eea1606 @powmedia Docs
authored
304 - A reference to the constructor function for your nested model
37872a1 @powmedia Docs
authored
305 - The referenced model must have it's own `schema` attribute
eea1606 @powmedia Docs
authored
306
307 Examples:
308
309 var schema = {
310 address: { type: 'NestedModel', model: Address }
311 };
312
313
f2fab62 @powmedia Links in readme
authored
314 <a name="editor-list"/>
f2ce846 @powmedia Update README.md
authored
315 ##List
eea1606 @powmedia Docs
authored
316
37872a1 @powmedia Docs
authored
317 Creates a sortable and editable list of items, which can be any of the above schema types, e.g. Object, Number, Text etc. Currently requires jQuery UI for creating dialogs etc.
eea1606 @powmedia Docs
authored
318
319 **`listType`**
320
321 - Defines the editor that will be used for each item in the list.
322 - Similar in use to the main 'type' schema attribute.
d3f6be7 @powmedia Rename TextField to Text
authored
323 - Defaults to 'Text'
324
45df2ee @powmedia Docs
authored
325 **`itemToString`**
f74af4b @powmedia Docs
authored
326
327 - Optional, but recommended when using listType 'Object'
328 - A function that returns a string representing how the object should be displayed in a list item.
9128501 @powmedia Add option to disable sorting on List editor
authored
329 - When listType is 'NestedModel', the model's `toString()` method will be used, unless a specific `itemToString()` function is defined on the schema.
330
331 **`sortable`**
332
333 - Optional. Set to false to disable drag and drop sorting
334
a90c213 @powmedia Add options to List editor: confirmDelete, confirmDeleteMsg
authored
335 **`confirmDelete`**
336
337 - Optional. Whether to prompt the user before removing an item. Defaults to false.
338
339 **`confirmDeleteMsg`**
340
341 - Optional. Message to display to the user before deleting an item.
342
f74af4b @powmedia Docs
authored
343
344 Examples:
345
346 var schema = {
45df2ee @powmedia Docs
authored
347 users: { type: 'List', listType: 'Object', itemToString: function(user) {
f74af4b @powmedia Docs
authored
348 return user.firstName + ' ' + user.lastName;
349 }
350 }
351 };
d3f6be7 @powmedia Rename TextField to Text
authored
352
353
01201a9 @powmedia Make List events cancellable
authored
354 **Events**
355
356 The following events are fired when the user actions an item:
8792f77 @powmedia Docs
authored
357
01201a9 @powmedia Make List events cancellable
authored
358 - `addItem`
359 - `editItem`
360 - `removeItem`
361
8792f77 @powmedia Docs
authored
362 Each event callback receives the relevant item value as an object, and a 'next' callback. To cancel the event and prevent the default action, do not run the callback.
363
364 This allows you to run asynchronous code, for example to check with the database that a username is available before adding a someone to the list:
01201a9 @powmedia Make List events cancellable
authored
365
366 var form = new Backbone.Form({ model: this.model }),
367 list = form.fields.list.editor;
368
8792f77 @powmedia Docs
authored
369 //Only add the item if the username is available
370 list.bind('addItem', function(item, next) {
371 database.getUser(item.username, function(user) {
372 if (user) {
373 //Item will not be added to the list because we don't call next();
374 alert('The username is already taken');
375 }
376 else {
377 //Username available; add the item to the list:
378 next();
379 }
380 });
01201a9 @powmedia Make List events cancellable
authored
381 });
382
383
f2fab62 @powmedia Links in readme
authored
384 <a name="editor-date"/>
f2ce846 @powmedia Update README.md
authored
385 ##Date
7f7e078 @powmedia Add 'minsInterval' option to DateTime editor
authored
386
387 Creates a jQuery UI datepicker
388
f2fab62 @powmedia Links in readme
authored
389
390 <a name="editor-datetime"/>
f2ce846 @powmedia Update README.md
authored
391 ##DateTime
7f7e078 @powmedia Add 'minsInterval' option to DateTime editor
authored
392
393 Creates a jQuery UI datepicker and time select field.
394
395 **`minsInterval`**
396
397 - Optional. Controls the numbers in the minutes dropdown. Defaults to 15, so it is populated with 0, 15, 30, and 45 minutes;
398
399
d3f6be7 @powmedia Rename TextField to Text
authored
400
fe19789 @powmedia Update README.md
authored
401 <a name="form-options"/>
f2ce846 @powmedia Update README.md
authored
402 #Form options
d3f6be7 @powmedia Rename TextField to Text
authored
403
404 **`model`**
405
406 The model to tie the form to. Calling `form.commit()` will update the model with new values.
407
408 **`data`**
409
410 If not using the `model` option, pass a native object through the `data` option. Then use `form.getValue()` to get the new values.
411
412 **`schema`**
413
414 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.
415
7e4355e @mjtamlyn Documentation for fieldsets.
mjtamlyn authored
416 **`fieldsets`**
417
418 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 `<legend>` tag; the list of fields will be treated as `fields` is below.
419
420 `fieldsets` takes priority over `fields`.
421
1667923 @powmedia Docs
authored
422 **`fields`**
423
424 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.
425
d3f6be7 @powmedia Rename TextField to Text
authored
426 **`idPrefix`**
427
428 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.
429
05cc2b0 @powmedia Docs for updated idPrefix behaviour. Closes #5
authored
430 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`.
431
35950ec @powmedia Update README.md
authored
432 [Back to top](#top)
433
434
435
436 <a name="validation"/>
437 #Validation
438
7d7e63f @powmedia Update README.md
authored
439 There are 2 levels of validation: schema validators and the regular built-in Backbone model validation. Backbone Forms will run both when either `form.commit()` or `form.validate()` are called.
440
441
442 ##Schema validation
443
444 Validators can be defined in several ways:
445
446 - **As a string** - Shorthand for adding a built-in validator. You can add custom validators to this list by adding them to `Backbone.Form.validators`. See the source for more information.
447 - **As an object** - For adding a built-in validator with options, e.g. overriding the default error message.
448 - **As a function** - Runs a custom validation function. Each validator the following arguments: `value` and `formValues`
449 - **As a regular expression** - Runs the built-in `regexp` validator with a custom regular expresssion.
450
451 ###Examples
452
453 var schema = {
454 //Built-in validator
455 name: { validators: ['required'] },
456
457 //Multiple built-in validators
458 email: { validators: ['required', 'email'] },
459
460 //Built-in editors with options:
461 password: { validators: [
462 { type: 'match', field: 'passwordConfirm', message: 'Passwords must match!' }
463 ] },
464
465 //Regular expression
466 foo: { validators: [/foo/] },
467
468 //Custom function
469 username: { validators: [
470 function checkUsername(value, formValues) {
471 var err = {
472 type: 'username',
473 message: 'Usernames must be at least 3 characters long'
474 };
475
476 if (value.length < 3) return err;
477 }
478 ] }
479 }
480
481
482 ###Handling errors
483
484 Error messages will be added to the field's help text area, and a customisable `bbf-error` class will be added to the field element so it can be styled with CSS.
485
486 Validation runs when `form.commit()` or `form.validate()` are called. If validation fails, an error object is returned with the `type` (validator that failed) and customisable `message`:
487
488 //Example returned errors from form validation:
489 {
490 name: { type: 'required', message: 'Required' }, //Error on the name field
491 email: { type: 'email', message: 'Invalid email address' }, //Error on the email field
492 _others: ['Custom model.validate() error'] //Error from model.validate()
493 }
494
495
496 ###Built-in validators
497
498 - **required**: Checks the field has been filled in
499 - **email**: Checks it is a valid email address
500 - **url**: Checks it is a valid URL
501 - **match**: Checks that the field matches another. The other field name must be set in the `field` option.
502 - **regexp**: Runs a regular expression. Requires the `regexp` option, which takes a compiled regular expression.
503
504
505 ##Customising error messages
506
a4756fb @powmedia Update README.md
authored
507 After including the Backbone Forms file, you can override the default error messages.
7d7e63f @powmedia Update README.md
authored
508
a4756fb @powmedia Update README.md
authored
509 {{mustache}} tags are supported; they will be replaced with the options passed into the validator configuration object. `{{value}}` is a special tag which is passed the current field value.
510
511 Backbone.Form.validators.errMessages.required = 'Please enter a value for this field.';
512
e6d69eb @powmedia Update README.md
authored
513 Backbone.Form.validators.errMessages.match = 'This value must match the value of {{field}}';
7d7e63f @powmedia Update README.md
authored
514
a4756fb @powmedia Update README.md
authored
515 Backbone.Form.validators.errMessages.email = '{{value}} is an invalid email address.';
7d7e63f @powmedia Update README.md
authored
516
517 You can also override the error message on a field by field basis by passing the `message` option in the validator config.
518
519
520 ##Model validation
521
522 If your models have a `validate()` method the errors will be added to the error object. To make the most of the validation system, the method should return an error object, keyed by the field object. If an unrecognised field is added, or just a string is returned, it will be added to the `_others` array of errors:
523
524 var User = Backbone.Model.extend({
525 validate: function(attrs) {
526 var errs = {};
527
528 if (usernameTaken(attrs.username)) errs.username = 'The username is taken'
529
530 if !_.isEmpty(errs) return errs;
531 }
532 })
533
534
535
536
537 ##Schema validators
35950ec @powmedia Update README.md
authored
538 Forms provide a `validate` method, which returns a dictionary of errors, or `null`. Validation is determined using the `validators` attribute on the schema (see above).
539
540 If you model provides a `validate` method, then this will be called when you call `Form.validate`. Forms are also validated when you call `commit`. See the Backbone documentation for more details on model validation.
541
7d7e63f @powmedia Update README.md
authored
542 Example:
543
544 //Schema definition:
545 var schema = {
546 name: { validators: ['required']
547 }
548
549 var errors = form.commit();
550
35950ec @powmedia Update README.md
authored
551 [Back to top](#top)
552
d3f6be7 @powmedia Rename TextField to Text
authored
553
554
fe19789 @powmedia Update README.md
authored
555 <a name="customising-templates"/>
f2ce846 @powmedia Update README.md
authored
556 #Customising templates
1e17bab @powmedia Docs
authored
557
558 Backbone-Forms comes with a few options for rendering HTML. To use another template pack, such as for [Bootstrap](http://twitter.github.com/bootstrap/), just include the .js file from the `templates` folder, after including `backbone-forms.js`.
559
3900a2b @powmedia Templating docs
authored
560 You can use your own custom templates by passing your templates (in Mustache syntax) and class names into `Backbone.Form.setTemplates()`. See the included templates files for examples.
561
562 You can include different field templates and then use them on a field-by-field basis by passing the `template` option in the field schema.
563
564 Example:
565
566 var templates = {
567 //field is the default template used
568 field: '\
569 <div>\
570 <label for="{{id}}">{{title}}</label>\
571 <div>{{editor}}</div> <div>{{help}}</div>\
572 </div>\
573 ',
574
575 //Specify an alternate field template
576 altField: '<div class="altField">{{editor}}</div>'
577 };
578
579 //Set the templates
580 Backbone.Form.setTemplates(templates, classNames);
581
582 var schema = {
583 age: { type: 'Number' }, //Uses the default 'field' template
584 name: { template: 'altField' } //Uses the 'altField' template
585 };
1e17bab @powmedia Docs
authored
586
35950ec @powmedia Update README.md
authored
587 [Back to top](#top)
588
1e17bab @powmedia Docs
authored
589
590
35950ec @powmedia Update README.md
authored
591 <a name="more"/>
592 #More
593
594 <a name="editors-without-forms"/>
fe19789 @powmedia Update README.md
authored
595 ##Editors without forms
d3f6be7 @powmedia Rename TextField to Text
authored
596
597 You can add editors by themselves, without being part of a form. For example:
598
599 var select = new Backbone.Form.editors.Select({
600 model: user,
601 key: 'country',
602 options: getCountries()
603 }).render();
604
605 //When done, apply selection to model:
606 select.commit();
eea1606 @powmedia Docs
authored
607
608
35950ec @powmedia Update README.md
authored
609 <a name="nested-fields"/>
610 ##Using nested fields
611
612 If you are using a schema with nested attributes (using the `Object` type), you may want to include only some of the nested fields in a form. This can be accomplished by using 'path' syntax as in the example below.
613
614 However, due to Backbone's lack of support for nested model attributes, getting and setting values will not work out of the box. For this to work as expected you must adapt your model's get() and set() methods to handle the path names, or simply use [DeepModel](http://github.com/powmedia/backbone-deep-model) which will handle paths for you automatically.
615
616 var Model = Backbone.DeepModel.extend({
617 schema: {
618 title: {},
619 author: { type: 'Object', subSchema: {
620 id: { type: 'Number' },
621 name: { type: 'Object', subSchema: {
622 first: {},
623 last: {}
624 }}
625 }}
626 }
627 });
628
629 var form = new Backbone.Form({
630 model: new Model,
631 fields: ['title', 'author.id', 'author.name.last']
632 }).render();
633
634
635 <a name="custom-editors"/>
0a9f430 @powmedia Update README.md
authored
636 ##Custom editors
eea1606 @powmedia Docs
authored
637
f2ce846 @powmedia Update README.md
authored
638 Writing a custom editor is simple. They must extend from Backbone.Form.editors.Base.
eea1606 @powmedia Docs
authored
639
640 var CustomEditor = Backbone.Form.editors.Base.extend({
646f014 @powmedia first commit
authored
641
642 tagName: 'input',
643
644 initialize: function(options) {
645 //Call parent constructor
eea1606 @powmedia Docs
authored
646 Backbone.Form.editors.Base.prototype.initialize.call(this, options);
646f014 @powmedia first commit
authored
647
648 //Custom setup code.
649 if (this.schema.customParam) this.doSomething();
650 },
651
652 render: function() {
4619643 @powmedia Docs
authored
653 this.setValue(this.value);
646f014 @powmedia first commit
authored
654
655 return this;
656 },
657
658 getValue: function() {
659 return $(this.el).val();
4619643 @powmedia Docs
authored
660 },
661
662 setValue: function(value) {
663 $(this.el).val(this.value);
646f014 @powmedia first commit
authored
664 }
665
666 });
667
eea1606 @powmedia Docs
authored
668 **Notes:**
3708193 @powmedia Fix readme chars
authored
669
4619643 @powmedia Docs
authored
670 - The editor must implement a getValue() and setValue().
646f014 @powmedia first commit
authored
671 - The original value is available through this.value.
672 - The field schema can be accessed via this.schema. This allows you to pass in custom parameters.
673
674
f2ce846 @powmedia Update README.md
authored
675
0a9f430 @powmedia Update README.md
authored
676 <a name="help"/>
677 ##Help & discussion
77a26cb @powmedia Add Google Groups link
authored
678
679 - [Google Groups](http://groups.google.com/group/backbone-forms)
680
f2ce846 @powmedia Update README.md
authored
681
0a9f430 @powmedia Update README.md
authored
682 ##Contributors
646f014 @powmedia first commit
authored
683
684 - Charles Davison - [powmedia](http://github.com/powmedia)
Something went wrong with that request. Please try again.