I'm using drupal 8.

Lets assume the following. I have created a content type called Foo. Using the presave hook(hook_entity_presave), I'm modifying some fields in that content type.

Firstly I want to determine if the entity I'm modifying is a Foo content type.

I've tried using Drupal\Core\Entity\EntityInterface $entity->getEntityType() however the return is object(Drupal\Core\Entity\ContentEntityType). So basically an object.

Since my knowledge of drupal 8 is not that great(yet) I assumed initially that it would return something more quantifiable like a string or something of the sort. Obviously I was wrong.

Secondly I want to NOT modify some fields if the fields already have a value. Again, I assume a simple isset or empty will do the trick. I could be wrong. If there are some other ways to do that, more drupal-like way, I'd be more than happy to understand it better.


You should be able to check the entity type and content type like this:

use Drupal\Core\Entity\EntityInterface;

function hook_entity_presave(EntityInterface $entity) {
  if($entity->getEntityTypeId == 'my_entity_type' && $entity->bundle() == 'my_content_type') {
    // Do your stuff here

Where my_entity_type is the entity type and my_content_type is the content type.

Adding Clive's answer, since the entity type you want to work with is already known to be a node, you can use hook_node_presave() instead of hook_entity_presave:

use Drupal\Core\Entity\EntityInterface;

function hook_entity_presave(EntityInterface $node) {
  if($node->bundle() == 'my_content_type') {
    // Do your stuff here
| improve this answer | |
  • It can also be shortened by implementing the more specific hook_node_presave as the OP knows the entity type up front – Clive Feb 14 '17 at 12:44
  • Good point - I updated my post with that information. – Jaypan Feb 14 '17 at 12:47
  • Perfect. the bundle() method returns exactly what I was looking for. getEntityTypeId() returns node which I expected since from what I gather almost everything in drupal is a node. Thanks for the help. – Andrew Feb 14 '17 at 12:48
  • Node is only one type of many different entities in Drupal 8. There are config entities, user entities taxonomy term entities, taxonomy vocabulary entities, and many more types of entities just in core alone. Modules will add even more entity types. – Jaypan Feb 14 '17 at 12:50
  • 1
    Thanks for the nice comments even while disagreeing with my methods. Much appreciated. – Jaypan Feb 14 '17 at 13:04

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.