2
  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');
}
$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();




2
  // get latest revision ID
  $latest_vid = \Drupal::entityTypeManager()
    ->getStorage('node')
    ->getLatestRevisionId($nid);

  // load latest revision
  $latest_revision = \Drupal::entityTypeManager()
    ->getStorage('node')
    ->loadRevision($latest_vid);

  // 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')
      ->save();
  }
1
  • perfect. Thank you.
    – esod
    Jul 2 at 17:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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