Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create JSON representation of complex form with nested objects and update backbone model

I have the following backbone model

var Page = Backbone.Model.extend({
    defaults: {
        id: null,
        metadata: {
            name: '',
            title: '',
            ...
        },
        children: []
        parent: null
    },
    urlRoot: '/api/page',
    initialize: function () {}
});

When I save the following form I need to create a JSON representation of this form and update the backbone model before saving it to the server. I need to do this because my form is dynamically created so I can not have hard coded selectors for looking for form names. Below is an example form.

<form>
    <label>Name:</label>
    <input type="text" name="metadata.name" value="">
    <label>Title:</label>
    <input type="text" name="metadata.title" value="">
    <label>Slug:</label>
    <input type="text" name="metadata.slug" value="">
    <label>Url:</label>
    <input type="text" name="metadata.url" value="">
    <button type="submit">Save</button>
</form>

What is the most efficient way of updating a backbone model based on HTML form data?

Edit

I found this answer here at stackoverflow, using square brackets instead of dots between objects. I think this technique works pretty good but maybe there are a similar way to serialize a form using dot notation?

like image 420
marcus Avatar asked Mar 05 '26 04:03

marcus


1 Answers

I ended up using this neat little library for converting my form to a JavaScript object

like image 180
marcus Avatar answered Mar 06 '26 18:03

marcus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!