0

I would like to populate the options of a select field with the attributes from a "static" model. For example I have a Model and a collections of US states:

State = Backbone.Model.extend({
    label:'',
    value:''
 }) ;
STATES = Backbone.Collection.extend({
    model: State
 });
 states =  [
    {label: "Select     ", value: '__' },
    {label: "Alabama     ", value: 'AL' },
    {label: "Alaska      ", value: 'AK' },
    {label: "Arizona     ", value: 'AZ' },
    ....];
  localstates = new app.STATES(states);  // or fetch the list of states from a RESTful site. 

I then using back form have any address view and I want to pass localstates into the Form to populate the options of the state field:

    UserAddress =  Backform.Form.extend({
    el: $("#personalInformation"),
     fields: [
       {name: "address1", label: "Address1", control: "input"},
       {name: "address2", label: "Address2", control: "input"},
       {name: "city", label: "City", control: "input"},
       {name: "state", label: "State", control: "select", 
         options: **localstates**,
       {name: "zip", label: "Zip Code", control: "input"},
       {control: "button", label: "Save to server"}
     ],
});

I'm guessing I need to somehow pass the states collection into the User Address view and then access the attributes. But I have not been able to find a good example of how to do this.

edit1: Ok this is a bit silly in this case but:

newstate = new app.STATES(app.states);
  var allstates =[];
app.newstate.forEach(function(state){
  allstates.push({"label": state.get("label"), "value" : state.get("value")});
})

Gives me and array I can use at localstate. Basically I just re-created my original array in this case. In the case where it was fetch from a server it would be useful, but is there a better way?

1 Answer 1

0

You can do localstates.toJSON() to get a copy of the values to use in the template.

See Collection.toJSON()

1
  • 1
    DUH! I knew there had to be a simple way.
    – magic
    Commented Mar 9, 2020 at 13:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.