1. My workflow is draft and publish.
  2. I create and publish a page.
  3. 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');

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->condition('cm.content_entity_id', $node->id());
$query->condition('cm.moderation_state', 'draft');
$result = $query->execute();
$record = $result->fetchAssoc();

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->setRevisionLogMessage('Draft created automatically');
//    $node->setNewRevision(FALSE);

1 Answer 1

  // get latest revision ID
  $latest_vid = \Drupal::entityTypeManager()

  // load latest revision
  $latest_revision = \Drupal::entityTypeManager()

  // set latest revision to published if is draft
  $is_draft = $latest_revision->moderation_state->value == 'draft';
  if ($is_draft) {
    $latest_revision->set('moderation_state', 'published')
  • perfect. Thank you.
    – esod
    Commented Jul 2, 2021 at 17:48
  • Works great for me too. Thanks.
    – Amit Sedai
    Commented Jun 13, 2022 at 9:54

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.