4

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.

1

1 Answer 1

8

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
  }
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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