14

I have a node object and I need to create revisions for that node programmatically. When I tried as follows it's not working. Instead it's creating new nodes. What am I doing wrong? How can I fix this?

$node = Node::create([
  'nid' => $nid, // My desired node ID for the revision.
  'type' => $bundle_type,
  'field1' => $value1,
  'field2' => $value2,
]);

$node->revision = TRUE;
$node->save();
$node->setPublished(true);
$nid = $node->id();
print 'Created revision for node' . $nid;

3 Answers 3

28

// Make this change a new revision
  $node->setNewRevision(TRUE);
  $node->revision_log = 'Created revision for node' . $nid;
  $node->setRevisionCreationTime(REQUEST_TIME);
  $node->setRevisionUserId($user_id);
  $node->save();

Use Above Code to create a revision. :)

7
  • How to specify the author when creating the revision ?
    – KTM
    May 17, 2017 at 11:52
  • 1
    Hi , when i create new revision for a node its set as the main node , instead of the revision . How can i solve this ? Is there an $node->is_current = FALSE; utility ??
    – KTM
    May 18, 2017 at 10:23
  • @RubberDuckIsKing It's in the answer, that's this part: $node->setRevisionUserId($user_id);
    – Dalin
    Sep 29, 2018 at 2:12
  • @RubberDuckIsKing It sounds like you're trying to create a forward draft revision (i.e. an unpublished draft). The exact details of that depends on whether you're using Workbench Moderation, Content Moderation, or something else. If the former, then something like $node->moderation_state->target_id = 'draft';
    – Dalin
    Sep 29, 2018 at 2:15
  • I thought I could get away with just calling $node->setNewRevision(TRUE) but it didn't work. You have to set everything above for it to work. Also, I used $node->setRevisionLogMessage('Updated'); rather than setting $node->revision_log directly.
    – neuquen
    May 16, 2019 at 20:43
2

For language specific revisions you can use below code sample:

$storage =\Drupal::entityTypeManager()->getStorage('node');
$revision = $storage->load($nid);
$revision = $revision->getTranslation($languageCode);
$revision->setRevisionCreationTime(\Drupal::time()->getCurrentTime());
$revision= $storage->createRevision($revision);
$revision->save();
1

If you have enabled the content moderation module, you must set the moderation state like this:

$node->moderation_state->value = 'draft';

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.