- My workflow is draft and publish.
- I create and publish a page.
- I create a draft of the page.
There is now the published page, but the latest revision is the draft.
How do I programmatically set as published the latest revision?
This code publishes the node.
$node = Node::load(nid);
// Publish and save the node.
if ($node->hasField('moderation_state')) {
$node->set('moderation_state', 'published');
}
$node->setPublished();
$node->save();
The node is already published. I want to publish the draft/latest revision of the node.
This query has some possibilities.
// Publish the draft of a node.
$query = \Drupal::database()->select('content_moderation_state_field_revision', 'cm');
// $query->fields('cm', ['moderation_state']);
$query->fields('cm');
$query->condition('cm.content_entity_id', $node->id());
$query->condition('cm.moderation_state', 'draft');
$result = $query->execute();
$record = $result->fetchAssoc();
print_r($record);
Since nodes can have more than one draft, I could add a LIMIT and an ORDER BY to the query. Simply changing the moderation_state in the content_moderation_state_field_revision table and rebuilding the cache doesn't publish the latest revision.
This code, altered slightly from EntityModerationForm.php worked once, but then didn't work again.
/** @var \Drupal\Core\Entity\ContentEntityStorageInterface $storage */
$storage = \Drupal::entityTypeManager()->getStorage($node->getEntityTypeId());
$entity = $storage->createRevision($node, $node->isDefaultRevision());
$new_state = 'published';
$entity->set('moderation_state', $new_state);
if ($entity instanceof RevisionLogInterface) {
$entity->setRevisionCreationTime(\Drupal::time()->getRequestTime());
$entity->setRevisionLogMessage('Draft created automatically');
$entity->setRevisionUserId(\Drupal::currentUser()->id());
}
// $node->setNewRevision(FALSE);
$entity->save();