powmedia / backbone-forms

Form framework for BackboneJS with nested forms, editable lists and validation
MIT License
2.17k stars 413 forks source link

Send the form ? #315

Closed Chrysweel closed 11 years ago

Chrysweel commented 11 years ago

Hello.

I discovered this bundle two days ago and it seems great.

But now I have a problem very silly , How can send my form ?

I read in the documentation that is with form.commit().

But how can I add a button to trigger event ? and send the data to APIrest?

Some example ?

thanks in advance

philfreo commented 11 years ago

form.commit() will populate a Backbone Model with the data from the form. You can "send" it with something like model.save() -- it's just regular Backbone code at that point, and you can add a button however you'd like - but one option is to use a custom form template.

Chrysweel commented 11 years ago

Thanks for to reply @philfreo .

I understand. But my problem is the following:

In my router I have:

var channel = new Channel();
$("#content").append(new FormView({model: channel}).el);

My FormView:

define(
function(require){

    var tpl         = require('text!templates/FormViewTpl.html'),
        template    = _.template(tpl);

    var FormView = Backbone.View.extend({

         events: {
          'click #submit': 'formCommit'
        },

        initialize:function () {
            this.render();
        },

        render: function () {
            var form = new Backbone.Form({
                    model: this.model,
                });
            $(this.el).append(form.render().el);
            $(this.el).append(template());
        },

        formCommit: function () {
            console.log('Here I am after click in button submit');
            How can I do to get the form and to do form.commit()  ????
        }
    });
    return FormView;
});

My FormViewTemplate now only show the button

<div>
It is the FormView
<button id='submit'>submit</button> 
</div>

Any idea ? I have it all wrong?

Thanks in advance !

exussum12 commented 11 years ago

in the FormView render function you will need to take a reference to form when you make it, so above events do form : null,

then at the bottom of render this.form = form

then in formCommit you can do

this.form.commit(); this.model.save()

Chrysweel commented 11 years ago

ahá! ok thank you very much @exussum12 !! : )

That was stupid, now it works.

But in the function formCommit I included a conditional:

formCommit: function () {
     var errors = this.form.commit();
            if (typeof errors === "undefined") {
                this.model.save();
            }
}

Thanks : )