0

What is the preferred way to add functionality to nodes? More explicitly stated: What is the node-entity equivalent of the Entity-class from the entity-API-module?

Sometimes you want to add methods to a entity. That is possible when using the entity-module, where each entity has a "entity class" property. You can take this entity class and extend it to your heart's content.

However, this is not possible with node-entities, since these don't use the "entity class" attribute.

So, the following code would work if drupal-core worked like the entity-module, but throws an error as is:

function myNode_entity_info_alter(&$info){
    $info['node']['entity class'] = 'MyNode';
}

class MyNode extends Entity{
    public function sayHi(){
        drupal_set_message("Hi!");
    }
}


function myNode_entity_load($entities, $type){
    if($type == 'node'){
        foreach ($entities as $entity) {
            $entity->sayHi(); # Error: Call to undefined method stdClass::sayHi()
        }
    }
}

How can I make this work with node-entities?

PS: as a follow-up question: is this any easier using drupal8?

1

I believe I have found something that does what I want: https://www.deeson.co.uk/labs/extending-entitydrupalwrapper

The basic idea is that, since drupal-core doesn't facilitate the extension of entity-classes, we use the entity-metadata-wrapper instead.

The above example would then be reformulated as such:

class MyNodeWrapper extends EntityDrupalWrapper{
    public function __construct($data) {
        parent::__construct('node', $data);
    }

    public function sayHi(){
        drupal_set_message("Hi!");
    }
}

function myNode_entity_load($entities, $type){
    if($type == 'node'){
        foreach ($entities as $entity) {
            $emw = new MyNodeWrapper($entity);
            $emw ->sayHi();
        }
    }
}

This appears to be a very reasonable approach. Only thing I dislike about it is that you can't use entity_metadata_wrapper to get the MyNodeWrapper-wrapper.

  • Is this possible in D8? – Codium Apr 6 '17 at 12:07
  • @drupality : this question seems to deal with the same problem from a drupal8 perspective. It appears that directly extending a node-class is still not the canonical approach, but quite possible, according to SiliconMind 's answer. There is also a more in-depth answer here . However, this way you extend the whole node class - I'm not sure if you can do this bundle-specific. – Michael Langbein Apr 6 '17 at 16:31
  • @drupality: as for extending the EntityMetadataWrapper instead of the node-class: it seems drupal8 has dropped EMW's and instead integrated them into the entity-classes themselves; thus making it unnecessary to first fetch an object and then wrap it in a EMW. – Michael Langbein Apr 6 '17 at 16:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.