Backbone Forms: Nested Model List Editor

An example showing how to construct a Form that uses Nested Models which can be added with a List editor.

by Glen Pike

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.3/backbone-min.js"></script>
<script src="https://rawgithub.com/powmedia/backbone-forms/master/distribution/backbone-forms.js"></script>
<script src="https://rawgithub.com/powmedia/backbone-forms/master/distribution/editors/list.js"></script>
<script src="https://rawgit.com/powmedia/backbone-forms/master/distribution/adapters/backbone.bootstrap-modal.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://rawgit.com/powmedia/backbone-forms/master/distribution/templates/bootstrap3.js"></script>
<div class="panel panel-default panel-primary">
  <div class="panel-heading">
    <h3 class="panel-title">Add your Team</h3>
  </div>
  <div class="panel-body">
  </div>
</div>

JavaScript

//Define a nested model - needs a schema on the model.
var MyNestedModel = Backbone.Model.extend({
  schema: {
    name: {
      type: 'Text',
      validators: ['required']
    },
    email: {
      type: 'Text',
      validators: ['required', 'email']
    },
    age: {
      type: 'Number',
      validators: ['required', 'number']
    }
  },
  //To string is how models in the list will appear in the "editor".
  toString: function() {
    var attrs = this.attributes;
    return attrs.name + ' @ ' + attrs.email + ', age ' + attrs.age;
  }
});

//Declare the main "parent" model
var MyModel = Backbone.Model.extend({
  schema: {
    teamName: {
      validators: ['required']
    },
    //We use our nested model in List Items here.
    participants: {
      type: 'List',
      itemType: 'NestedModel',
      model: MyNestedModel
    }
  }
});

//Pre-existing nested model values are defined as objects
var myNestedModel = {
  name: 'Backbone',
  email: '[email protected]',
  age: 4
};

var myNestedModel2 = {
  name: 'Forms',
  email: '[email protected]',
  age: 12
};

//Create an instance of the parent model, with nested values
var myModel = new MyModel({
  teamName: 'Team-X',
  //Add an array of objects to pre-populate the nested model list
  participants: [myNestedModel, myNestedModel2]
});

//This needs to be set if you want to use the modal to add new nested models
Backbone.Form.editors.List.Modal.ModalAdapter = Backbone.BootstrapModal;

var form = new Backbone.Form({
  model: myModel,
  submitButton: 'Submit',
  validate: true
}).render().on('submit', function(e) {
  e.preventDefault();
  this.validate();
});

$('.panel-body').html(form.el);