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:
revision_translation_affectedremains NULL, which means that the revision will currently not appear in the revision UI (#2882334: Revisions are not visible for some nodes)- the
entity_revision_createhook is not invoked (#3031405: New hook_entity_revision_create() is not always fired when new revisions are created) - the revision user is not set to the current user and the revision time is not set to the current time (#2869056: Automatically set revision user/log information/created time on entity revisions)
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
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
Comment #2
dieterholvoet commentedMaybe we could even add an optional $message argument, simplifying a lot of use cases even more:
Comment #4
dieterholvoet commentedComment #5
dieterholvoet commented