Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By claudiu.cristea on
Change record status:
Published (View all published change records)
Project:
Introduced in branch:
8.3.x
Introduced in version:
8.3.0
Issue links:
Description:
Content entities that need a published/unpublished flag base field are now able to declare a "published" entity key in their entity type annotation. Such entities should implement the new \Drupal\Core\Entity\EntityPublishedInterface
and use the \Drupal\Core\Entity\EntityPublishedTrait
trait. The interface can be implemented directly, by the entity class, or by the entity specialised interface.
use Drupal\Core\Entity\EntityPublishedInterface;
use Drupal\Core\Entity\EntityPublishedTrait;
use ...
/**
* @ContentEntityType(
* id = "custom_entity",
* ...
* entity_keys = {
* "id" = "id",
* "published" = "status",
* "label" = "label",
* },
* ...
* )
*/
class CustomEntity extends ContentEntityBase implements CustomEntityInterface, EntityPublishedInterface {
use EntityPublishedTrait;
...
}
Entities defined in this way can benefit of the new provided methods to set the published status ON/OFF and are able to inspect the status of the published flag field:
$storage = \Drupal::entityTypeManager()->getStorage('custom_entity');
$entity = $storage->load(123);
// Reverse the published status.
if ($entity->isPublished()) {
$entity->setUnpublished();
}
else {
$entity->setPublished();
}
$entity->save()
Impacts:
Module developers
Themers