Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

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