Problem/Motivation

I always assumed that the following code would be enough to create a new revision programatically:

$entity->setNewRevision();
$entity->setRevisionLogMessage('Did some update.');
$entity->save();

However, this is not the case. Multiple things are wrong with this approach:

This means that doing something as simple as creating a new revision requires a lot of custom code and most of all, a lot of in-depth knowledge about revisions in order to get it right.

Proposed resolution

Add a RevisionableInterface::createRevision() method that, just like EntityInterface::save(), delegates to the equivalent method on the entity storage. Add #[NoDiscard] to the method to make clear that it returns a new entity object (#3560672: [policy, no patch] Decide if and where to adopt the #[NoDiscard] attribute).

$revision = $entity->createRevision();
$revision->setRevisionLogMessage('Did some update.');
$revision->save();

This fixes the first two points mentioned above, but not the revision user and the revision time defaults. The code that sets these could be added to ContentEntityStorageBase::createRevision() instead of being spread across ContentEntityBase::preSave() and EditorialContentEntityBase::preSaveRevision() as is currently being done in the MR of #2869056: Automatically set revision user/log information/created time on entity revisions. Grouping all code related to creating revisions together would make it a lot easier for developers to understand what's going on when creating a new revision.

Remaining tasks

User interface changes

Introduced terminology

API changes

Data model changes

Release notes snippet

Issue fork drupal-3626980

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

dieterholvoet created an issue. See original summary.

dieterholvoet’s picture

Maybe we could even add an optional $message argument, simplifying a lot of use cases even more:

$revision = $entity->createRevision(message: 'Did some update.');
$revision->save();

dieterholvoet’s picture

Status: Active » Needs review
dieterholvoet’s picture

Issue summary: View changes