By gábor hojtsy on
Change record status:
Published (View all published change records)
Project:
Introduced in branch:
8.x
Introduced in version:
8.0
Issue links:
Description:
The NodeChangedConstraint and NodeChangedConstraintValidator that were previously only available for nodes have now been generalized for all entities. This constraint validator is useful to validate entities to avoid cross-edit overwrites. When user A and user B open an entity for editing and user B saves before user A, user A should get a validation error for editing an old version of the entity.
The constraint and validator are available generically. To use it, do the following:
- Add a
changedtimestamp to your entity base fields (in your entity database schema for example) and define it with thebaseFieldDefinitions()method, while assigning theEntityChangedconstraint (excerpt fromNode.php):
$properties['changed'] = array( 'label' => t('Changed'), 'description' => t('The time that the node was last edited.'), 'type' => 'integer_field', 'property_constraints' => array( 'value' => array('EntityChanged' => array()), ), ); - Make your entity class implement
EntityChangedInterface, so that it provides thechangedtimestamp via agetChangedTime()method. SeeNodeInterface.phpandNode.phpin core for example. - By associating the constraint with the base field and implementing the interface, the constraint will be able to retrieve the
changedtimestamps on the edited and saved entities and compare them for detecting editing conflicts. To get the validation messages, use:
$violations = $entity->validate();If your copy of the entity has an older
changedtimestamp than the one saved in the system, you'll get a validation error in the returned array. In practice you'll get data like:// This will be 'changed.0.value'. $property = $violations[0]->getPropertyPath(); // This will be t('The content has either been modified by another user, or you have already submitted modifications. As a result, your changes cannot be saved.'); $message = $violations[0]->getMessage();
Impacts:
Module developers