I'm on on a D9.4.x clean installation, and I am having inconsistent behavior when trying to editing and change the moderated state of a content type which is also translatable in EN and ITA.
If I try the following code:
function test_node_publish() {
$node = \Drupal::entityTypeManager()->getStorage('node')->load(2);
$status = 'draft';
test_node_edit($node, 'new english title', $status);
test_node_edit($node->getTranslation('it'), 'nuovo titolo ita', $status);
$node->save();
}
function test_node_edit($node, $title, $status) {
$node->setTitle($title);
$node->set('moderation_state', $status);
$node->setRevisionLogMessage('Changed moderation state to ' . $status);
$node->setRevisionUserId(1);
}
It seems to work when the moderation state is draft
.
However, when using publish
state the node is published with the older "title" values (the one of the last published version) and not the ones of the most recent draft.
If I try the following code, from this answer:
function publish_test() {
$latest_vid = \Drupal::entityTypeManager()
->getStorage('node')
->getLatestRevisionId(2);
// load latest revision
$latest_revision = \Drupal::entityTypeManager()
->getStorage('node')
->loadRevision($latest_vid);
$latest_revision->set('moderation_state', 'published')
->save();
}
function publish_test_ita() {
$latest_vid = \Drupal::entityTypeManager()
->getStorage('node')
->getLatestRevisionId(2);
// load latest revision
$latest_revision = \Drupal::entityTypeManager()
->getStorage('node')
->loadRevision($latest_vid);
$latest_revision->getTranslation('it')->set('moderation_state', 'published')
->save();
}
When publishing the EN version, the IT get unpublished. In the revision page, the message is
Changed moderation state to draft (Published)
In the edit form, the translation seems to be published, but both in the view mode and on the node/2/translations
tab the IT translation is actually in draft.
After running publish_test_ita()
, the IT translation get published, but the EN seems to lose the Current revision
flag. (see screenshot).
What is the correct way to edit fields values and moderation states when the content is also translatable?