Bart Henry
Bart Henry

Reputation: 25

Backbone-Forms - best way to change select options

I'm looking for a best method for changing select options on demand. I know, that I can swap options by using setOptions method on form field, but it doesn't help in my case. It would be better to change options before form is created.

In my model I have many fields with similiar schema:

field:{type:"Select",title:"", validators: ['required'], options:new App.Collections.SomeCollection()}

Say, I need to create form and I don't want to have all the elements of SomeCollection as select options. I need few of them and I can fetch that collection, that's no problem. Is there any way to swap options before creating Backbone Forms instance? I've tried it, but without success, so far. I've already faced this problem second time and I've created select manually (outside of Backbone Forms engine, so without use of data-fields property) and then also manually inserted options, but I believe that there's better idea.

Thanks for any ideas!

Upvotes: 1

Views: 740

Answers (1)

nanobar
nanobar

Reputation: 66355

Use a filtered version of your collection. Instead of passing field.options to whatever is responsible for mapping and rendering out the options, pass a filtered version of the collection.

var filteredOptions = field.options.filter(function (optionModel) {
    // Some filter boolean check (true adds it to filteredOptions).
    return optionModel.get('key') !== 'UK';
});

You do this each time you need to re-render the select with a new filtered version of the collection.

P.S. The filter comes from underscore.

Upvotes: 2

Related Questions