jDrupal icon indicating copy to clipboard operation
jDrupal copied to clipboard

How to add support for a custom entity?

Open luxio opened this issue 9 years ago • 7 comments

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

luxio avatar Sep 02 '16 10:09 luxio

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.

signalpoint avatar Sep 02 '16 19:09 signalpoint

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()?

luxio avatar Sep 03 '16 10:09 luxio

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

signalpoint avatar Sep 03 '16 14:09 signalpoint

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

kentr avatar Sep 03 '16 15:09 kentr

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

signalpoint avatar Sep 03 '16 16:09 signalpoint

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

kentr avatar Sep 03 '16 18:09 kentr

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

signalpoint avatar Feb 03 '17 05:02 signalpoint