signalpoint / jDrupal

A JavaScript Library and API for Drupal Applications
http://jdrupal.tylerfrankenstein.com/
GNU General Public License v2.0
76 stars 38 forks source link

How to add support for a custom entity? #47

Open luxio opened 8 years ago

luxio commented 8 years ago

Is there a way (hooks) to add support for a custom entity type in jDurpal?

signalpoint commented 8 years ago

You can use entity_load(), entity_save() and entity_delete() with jDrupal and it should do most of it for you. For any custom entity, you do need to tell jDrupal about the primary key though. For example, to support Commerce Orders, I needed to add this function:

function commerce_order_primary_key() {
  return 'order_id';
}

That should be it. Then I typically make a wrapper function, for example:

function commerce_order_load(order_id, options) {
  entity_load('commerce_order', order_id, options);
}

Then callers can more easily use it:

function foo() {
  commerce_order_load(123, {
    success: function(order) {
      console.log(order);
    }
  });
}

I'll also make wrappers for save/delete following the same guidelines.

luxio commented 8 years ago

Thanks. I have tried this, but I get an error when loading an entity:

WARNING: entity_load - unsupported type: my_entity_type

Do I have to add my custom entity to entity_types()?

signalpoint commented 8 years ago

@luxio It looks like we'll need some type of hook to allow people to declare an entity type:

https://github.com/easystreet3/jDrupal/blob/7.x-1.x/src/entity.js#L547

Right now it's hard coded in for core entity types. I'd love it if it was dynamic and automatically knew what was on the Drupal site. Thoughts?

kentr commented 8 years ago

What about just redefining entity_types() in the custom code? Something like this:

// redefine entity_types()
var core_enity_types = entity_types;
entity_types = function() {
  return core_entity_types().concat('my_entity_type');
}

// load wrapper.
function my_entity_type_load(order_id, options) {
  entity_load('my_entity_type', my_entity_id, options);
}
signalpoint commented 8 years ago

@kentr excellent, very clever. That'll work.

kentr commented 8 years ago

Cleaner version, based on this example

// Decorate entity_types().
entity_types = (function() {
  var core_types = entity_types;
  return function() {
    return core_types.apply(this, arguments).concat('my_entity_type');
  }
})();

// load() wrapper.
function my_entity_type_load(order_id, options) {
  entity_load('my_entity_type', my_entity_id, options);
}
signalpoint commented 7 years ago

FYI, jDrupal can now utilize Services Entity to support all entity types (core and custom): https://github.com/signalpoint/jDrupal/issues/60