3 namespace Drupal\Core\Entity;
5 use Drupal\Core\Entity\Exception\UnsupportedEntityTypeDefinitionException;
6 use Drupal\Core\Field\BaseFieldDefinition;
7 use Drupal\Core\StringTranslation\TranslatableMarkup;
10 * Provides a trait for published status.
12 trait EntityPublishedTrait {
15 * Returns an array of base field definitions for publishing status.
17 * @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
18 * The entity type to add the publishing status field to.
20 * @return \Drupal\Core\Field\BaseFieldDefinition[]
21 * An array of base field definitions.
23 * @throws \Drupal\Core\Entity\Exception\UnsupportedEntityTypeDefinitionException
24 * Thrown when the entity type does not implement EntityPublishedInterface
25 * or if it does not have a "published" entity key.
27 public static function publishedBaseFieldDefinitions(EntityTypeInterface $entity_type) {
28 if (!is_subclass_of($entity_type->getClass(), EntityPublishedInterface::class)) {
29 throw new UnsupportedEntityTypeDefinitionException('The entity type ' . $entity_type->id() . ' does not implement \Drupal\Core\Entity\EntityPublishedInterface.');
31 if (!$entity_type->hasKey('published')) {
32 throw new UnsupportedEntityTypeDefinitionException('The entity type ' . $entity_type->id() . ' does not have a "published" entity key.');
35 return [$entity_type->getKey('published') => BaseFieldDefinition::create('boolean')
36 ->setLabel(new TranslatableMarkup('Publishing status'))
37 ->setDescription(new TranslatableMarkup('A boolean indicating the published state.'))
38 ->setRevisionable(TRUE)
39 ->setTranslatable(TRUE)
40 ->setDefaultValue(TRUE)];
46 public function isPublished() {
47 $key = $this->getEntityType()->getKey('published');
48 return (bool) $this->get($key)->value;
54 public function setPublished($published = NULL) {
55 if ($published !== NULL) {
56 @trigger_error('The $published parameter is deprecated since version 8.3.x and will be removed in 9.0.0.', E_USER_DEPRECATED);
57 $value = (bool) $published;
62 $key = $this->getEntityType()->getKey('published');
63 $this->set($key, $value);
71 public function setUnpublished() {
72 $key = $this->getEntityType()->getKey('published');
73 $this->set($key, FALSE);