Default revisions, forward revisions, and past revisions

Submitted by timmillwood on Wed, 15/02/2017 - 10:15

Drupal 8 has two revisionable entity types, Node and Block Content. When working with revisions it's key to understand the different states a revision can have.

If you have a node with the ID 1 you can load it with Node::load(1);, this will load the default revision. You may have 200 revisions of node 1, but the default revision is the one which is loaded by default.

Currently forward revisions are revisions with a higher revision ID than the default revision, and past revisions are revisions with a lower revision ID than the default revision.

Creating a forward revision is as simple as creating a new revision, which is not the default.

$node->setNewRevision(TRUE);
$node->isDefaultRevision(FALSE);
$node->save();

The code above assumes $node is an existing node revision object. First we enforce a new revision created, then set that new revision to not be the default revision, and save. If you were to look in the database node_field_data would have the original revision information as it's still the default, but in node_field_revision you will see a revision with a higher revision ID (vid), this is the forward revision we just created.

Using the same code without the isDefaultRevision(FALSE) line will create a new default revision as this is the standard behaviour when saving an entity. The original revision will then become a past revision.