Coder Social home page Coder Social logo

Comments (20)

powmedia avatar powmedia commented on May 20, 2024

I'm not familiar with Backbone.Relational but from the samples you've posted looks like this could be a relatively easy fix. Don't think it would belong in the main codebase though, I think the best way to handle this would be to create a new editor e.g. RelationalNestedModel, which extends from Backbone.Form.editors.NestedModel and make the required changes in there.

from backbone-forms.

moskrc avatar moskrc commented on May 20, 2024

Thanks! Nice idea.

from backbone-forms.

powmedia avatar powmedia commented on May 20, 2024

Let me know if you have any questions on creating the new editor but you can see a brief example in the Readme docs and check the source to see how the other editors are implemented.

from backbone-forms.

gerardobort avatar gerardobort commented on May 20, 2024

For all those who wanted to know how to get these awesome libraries integrated, here is a hack... I hope this help :)

  editors.List = editors.Base.extend({

    events: {
      'click [data-action="add"]': function(event) {
        event.preventDefault();
        this.addItem();
      }   
    },  

    initialize: function(options) {
      editors.Base.prototype.initialize.call(this, options);

      // here starts the magic
      if (options.model instanceof Backbone.RelationalModel) {
        this.value = options.model.get(options.key).toJSON();
      } 
      // here finish the magic

      var schema = this.schema;
      if (!schema) throw "Missing required option 'schema'";

// ...

@powmedia I think would be really cool if you introduce this (or something like) change in order to integrate backbone-forms with backbone-relational... I started using this last one recently and it's life changing.

from backbone-forms.

powmedia avatar powmedia commented on May 20, 2024

Thanks, I'll look into adding this soon. Do the other editors (especially NestedModel) all work with backbone relational already?

On 3 Aug 2012, at 05:29, Gerardo [email protected] wrote:

For all those who wanted to know how to get these awesome libraries integrated, here is a hack... I hope this help :)

 editors.List = editors.Base.extend({

   events: {
     'click [data-action="add"]': function(event) {
       event.preventDefault();
       this.addItem();
     }   
   },  

   initialize: function(options) {
     editors.Base.prototype.initialize.call(this, options);

     // here starts the magic
     if (options.model instanceof Backbone.RelationalModel) {
       this.value = options.model.get(options.key).toJSON();
     } 
     // here finish the magic

     var schema = this.schema;
     if (!schema) throw "Missing required option 'schema'";

// ...

@powmedia I think would be really cool if you introduce this (or something like) change in order to integrate backbone-forms with backbone-relational... I started using this last one recently and it's life changing.


Reply to this email directly or view it on GitHub:
#78 (comment)

from backbone-forms.

gerardobort avatar gerardobort commented on May 20, 2024

Yes, it works perfectly. This snippet converts the List value from being a Backbone.Collection into a plain array of models (NestedModel is required) just before applying the schema. This is the one thing that makes these two modules incompatible (Collection != Array).
One particular thing that was causing some problems during the form.commit() (that was making to reset the Model instead of saving it) is that is needed to set the includeInJSON as false.. ej:

reverseRelation: {
            key: 'livesIn',
            includeInJSON: false
//...

And this is how I finally moved out the hack into a separate file, just to not touch the original library... (I also added a check for the value type before converting it =)

        Backbone.Form.editors.Base.prototype._initialize = Backbone.Form.editors.Base.prototype.initialize;
        Backbone.Form.editors.Base.prototype.initialize = function(options) {
            Backbone.Form.editors.Base.prototype._initialize.call(this, options);
            // this patch adds compatibility between backbone-forms and backbone-relational libraries
            if (options.model instanceof Backbone.RelationalModel && options.model.get(options.key) instanceof Backbone.Collection) {
                this.value = options.model.get(options.key).toJSON();
            }   
        };

Here, a better example of how I used it...

    Backbone.RoleDefinitionModel = Backbone.RelationalModel.extend({

        defaults: {
            name: "",
            type: ""
        },

        schema: {
            name: { title: 'Role Name' },
            type: { dataType: 'Text', type: 'Select', title: 'Privileges',
                options: [
                    { val: 'admin', label: 'Administrator' },
                    { val: 'cooperator', label: 'Cooperator' },
                    { val: 'follower', label: 'Follower' },
            ]}
        },
    });

    var GroupModel = Backbone.RelationalModel.extend({

        urlRoot: "api/group",

        defaults: {
            id: null,
            type: 'public',
            name: '',
            groupname: '',
        },

        relations: [{
                type: Backbone.HasMany,
                key: 'role_definitions',
                relatedModel: 'Backbone.RoleDefinitionModel',
                collectionType: 'Backbone.Collection',
                reverseRelation: {
                    key: 'group',
                    includeInJSON: false // this is a must! - if not set to false can cause the model stops being saved correctly
                }
        }],

        schema: {
            name:       { dataType: 'Text', title: 'Group Name', validators: ['required'] },
            groupname:  { dataType: 'Text', title: 'henb.it/group/', validators: ['required'] },
            role_definitions: {
                type: 'List', itemType: 'NestedModel', model: Backbone.RoleDefinitionModel, title: 'Role Definitions',
                itemToString: function(role) {
                    return role.name + ' (' + role.type + ')' +
                        '<div data-role data-role-name="' + role.name + '"></div>';
                },
            },
        },

        addRole: function (roleName, roleType) {
            this.get('role_definitions').add(new Backbone.RoleDefinitionModel({
                name: roleName,
                type: roleType
            }));
        },
    };

from backbone-forms.

GregSilverman avatar GregSilverman commented on May 20, 2024

Hey, thanks for the hack. This helps with what I am about to do using backbone-associations (a lightweight version of backbone-relational) with backbone-forms, Cool stuff!

from backbone-forms.

monokrome avatar monokrome commented on May 20, 2024

@powmedia Any updates / progress regarding something like this being brought into the official codebase?

from backbone-forms.

monokrome avatar monokrome commented on May 20, 2024

@gerardobort It seems like your hack works in simple situations, but a lot of functionality is missing. For instance, when providing:

form = new Backbone.Form
    model: SomeModel
    fields: ['someField', 'someRelatedField.someField']

You are not properly able to refer to related fields. Another issue is that your data is a JSON object after commit() has been called. This might only be the case for a HasOne relationship, since I haven't tested HasMany. Either way, the data is broken from relational's point of view, since the data expected from relational is a RelationalModel - not a JSON object.

from backbone-forms.

gerardobort avatar gerardobort commented on May 20, 2024

@monokrome the hack I've provided works perfectly using NestedModel (look at my example above for "role_definitions"). It wasn't supposed to support the "dot notation" you mention (I'm not sure if that's part of the current bbf syntax).
Using NestedModel, after commit you get the model and its nested childs as RelationalModels... it works even with HasMany and any other options. Please, let me know if that's not what you meant.

from backbone-forms.

gerardobort avatar gerardobort commented on May 20, 2024

@monokrome regarding the JSON object as result that you say, Backbone Relational takes care of that... when the set() method is called on the parent model, at that point is when the JSON object fills also the children models.

from backbone-forms.

monokrome avatar monokrome commented on May 20, 2024

@gerardobort I think that a better way to describe my issue is that your hack focuses on the case where the relation is a collection, but what about the case of a HasOne relationship where the related object is a single model?

You are correct about the dot syntax not being a BBF thing, however. Ends up it's provided by this project:

https://github.com/powmedia/backbone-deep-model

from backbone-forms.

monokrome avatar monokrome commented on May 20, 2024

I also have noticed that Backbone Relational doesn't automatically convert JSON into model data when using set. Maybe that's something from an older version of relational?

https://github.com/PaulUithol/Backbone-relational/blob/master/backbone-relational.js#L1316

from backbone-forms.

gerardobort avatar gerardobort commented on May 20, 2024

@monokrome well, for the collection I used the List editor, and as itemType the NestedModel. Did you tried to use NestedModel as editor instead? I think this shoul work for the HasOne situation.

from backbone-forms.

monokrome avatar monokrome commented on May 20, 2024

@gerardobort I am trying to use type: NestedModel, and it's a HasOne relation - so, I shouldn't need to use List. My issue is that form.commit() gets called, and the value for my nested model is replaced with a JSON object instead of a nested model.

from backbone-forms.

philfreo avatar philfreo commented on May 20, 2024

@monokrome it'd be easy enough to override backbone.form's commit() to set your model json in a different way - you'd just need to figure out how you want it to work first.

note: backbone-relational doesn't really have a working build for backbone 1.0.0 yet :(

from backbone-forms.

monokrome avatar monokrome commented on May 20, 2024

I was expecting something like this hack to convert the JSON into a RelationalModel, since backbone-relational wont do this by default upon commit():

Backbone.Form.prototype._commit = Backbone.Form.prototype.commit;

Backbone.Form.prototype.commit = (function (options) {
    var key, model;

    Backbone.Form.prototype._commit.apply(this, [options]);

    if (typeof Backbone.RelationalModel != 'undefined') {
        if (this.model instanceof Backbone.RelationalModel) {
            for (key in this.schema) {
                if (typeof this.schema[key] == 'object' &&
                    typeof this.schema[key].type != 'undefined' &&
                    this.schema[key].type == 'NestedModel') {

                    if (this.model.get(key) instanceof Backbone.Model != true) {
                        model = new (this.schema[key].model)(this.model.get(key));

                        this.model.set(key, model);
                    }
                }
            }
        }
    }
});

from backbone-forms.

monokrome avatar monokrome commented on May 20, 2024

@gerardobort I have noticed that in your hack, options.key is undefined. I wonder if I am just using the library wrong at this point. What does options.key refer to?

from backbone-forms.

gerardobort avatar gerardobort commented on May 20, 2024

@monokrome I think that should refer to the attribute's name of the parent model.. the same that you specify in the schema... I've looked at the current source and it still using it (my hack is from 9 months ago)...
Check this line ... https://github.com/powmedia/backbone-forms/blob/master/src/editors.js#L32

from backbone-forms.

gerardobort avatar gerardobort commented on May 20, 2024

@monokrome I've created a repository for testing this integration stuff... the only problem I'd when using HasOne relation is a warning on Backbone-Relational, but regardless that warning, the integration went very well. The example includes HasOne and HasMany both working at the same time. Try it yourself!
http://github.com/gerardobort/bbf-bbr-integration

regards

from backbone-forms.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.