0

I created a custom content entity type and a bundle of this entity type. The custom content entity is presented as PHP class; the entity bundle is defined in a configuration file.

I created the Entity class on my own, programmatically; the entity bundle was created via the Drupal UI.

Now I am wondering why Drupal is creating a configuration file instead of a subclass. Do you know if it is possible to override class methods from the base entity for the specific entity bundle?

1
  • 2
    The Entity API was not intended for the use case that you are describing. Bundles are meant to describe different configurations of an Entity type, but not different functionally. There a couple of patterns that have been used, even in Drupal 7, to do such, but it in Drupal 8, but that's an opinionated answer.
    – mradcliffe
    Commented Dec 9, 2019 at 13:27

1 Answer 1

1

Do you know if it is possible to override class methods from the base entity for the specific entity bundle?

Yes, this is possible. In code you can only override globally, but a class instance is always bundle specific. This is the only required field when creating a content entity with bundles. So the bundle is always set and you can use it in a condition in the overridden method and defer to the parent method for other bundles.

For example if you had a getTitle() method you could modify the title for a specific bundle:

  /**
   * {@inheritdoc}
   */
  public function getTitle() {
    if ($this->bundle() == 'foo') {
      return 'bar';
    }

    return parent::getTitle();
  }

Your Answer

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

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