现在有已出版的一页,但最新的修订是草案。
如何以编程方式设置已发布的最新版本?
此代码发布节点。
$node = Node::load(nid);
// Publish and save the node.
if ($node->hasField('moderation_state')) {
$node->set('moderation_state', 'published');
}
$node->setPublished();
$node->save();节点已经发布。我想发布节点的草稿/最新版本。
这个查询有一些可能性。
// 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);因为节点可以有多个草案,所以我可以为查询添加一个限制和一个订单。简单地更改content_moderation_state_field_revision表中的content_moderation_state_field_revision并重新构建缓存并不会发布最新的修订版。
这段与EntityModerationForm.php略有不同的代码曾经工作过一次,但之后就不再工作了。
/** @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();发布于 2021-07-01 23:53:33
// 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();
}https://drupal.stackexchange.com/questions/303872
复制相似问题