Sudo
Sudo

Reputation: 559

Create dynamic form fields using jquery and backbone js

I have an application which uses backbone js and jquery. I need to generate templates dynamically based on what response i get from the server. The scenario is like this... I have a dropdown of templates which I can choose, after I select any template from the dropdown, an api is called for that template which provides me with a structure like this

items:[
{
    "vars":
           {
               "name":
                      {
                           "required": false,
                           "default": "abc"
                      },
               "address":
                      {
                           "required": false,
                           "default": "xyz"
                       }
           }
    "tables": {}
}]

So how can I create dynamic form elements using this kind of server response?

Upvotes: 1

Views: 2961

Answers (1)

jevakallio
jevakallio

Reputation: 35950

You could use the backbone-forms plugin, and map your server response to a form object. Something like:

var data = {};
var schema = {};
var item = _.first(items);

_.each(item.vars, function(value, key) {
  data[key] = value.default;
  schema[key] = {
    type:"Text",
    validators:value.required ? ['required'] : undefined
  };
});

var form = new Backbone.Form({data:data, schema:schema}).render();

That's just a simple, untested example. Check out the backbone-forms documentation, and see if it can do what you need.

Upvotes: 3

Related Questions