Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support backbone-relational #78

Closed
moskrc opened this issue Jun 25, 2012 · 20 comments
Closed

Support backbone-relational #78

moskrc opened this issue Jun 25, 2012 · 20 comments

Comments

@moskrc
Copy link

moskrc commented Jun 25, 2012

Hi,

https://github.com/PaulUithol/Backbone-relational

ItemText.Model = Backbone.RelationalModel.extend({

    schema: {
        item:  {
            type: 'NestedModel',
            model: Item.Model
        },
        text:  { type: 'TextArea',validators: ['required'] }
    },
    relations:[
        {
            type:Backbone.HasOne,
            key:'item',
            relatedModel:Item.Model,
            includeInJSON:true
        }
    ]
});

Schema for Item didn't work. Because relational change model attributes. See...

Without backbone-relational

attributes: Object
    id: "25"
    item: Object
        id: "25"
        layer: "/api/v1/layers/46/"
        name: "XXXXXXXXXXXX"
        position_x: 23
        position_y: 27
        position_z: 0
        resource_uri: "/api/v1/items/25/"  
        __proto__: Object
    resource_uri: "/api/v1/texts/25/"
    text: "qqqqq"

With backbone relational:

attributes: Object
    id: "25"
    item: Object
        attributes: Object
            id: "25"
            layer: "/api/v1/layers/46/"
            name: "XXXXXXXXXXXX"
            position_x: 23
            position_y: 27
            position_z: 0
            resource_uri: "/api/v1/items/25/"
            __proto__: Object
        changed: Object
        cid: "c16"
        collection: Object
        id: "/api/v1/items/25/"
        __proto__: Object
    resource_uri: "/api/v1/texts/25/"
    text: "qqqqq"
@powmedia
Copy link
Owner

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.

@moskrc
Copy link
Author

moskrc commented Jun 25, 2012

Thanks! Nice idea.

@powmedia
Copy link
Owner

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.

@gerardobort
Copy link

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.

@powmedia
Copy link
Owner

powmedia commented Aug 3, 2012

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 Bortreply@reply.github.com 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)

@gerardobort
Copy link

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
            }));
        },
    };

@GregSilverman
Copy link

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!

@monokrome
Copy link

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

@monokrome
Copy link

@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.

@gerardobort
Copy link

@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.

@gerardobort
Copy link

@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.

@monokrome
Copy link

@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

@monokrome
Copy link

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

@gerardobort
Copy link

@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.

@monokrome
Copy link

@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.

@philfreo
Copy link
Collaborator

@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 :(

@monokrome
Copy link

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);
                    }
                }
            }
        }
    }
});

@monokrome
Copy link

@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?

@gerardobort
Copy link

@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

@gerardobort
Copy link

@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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants