Drupal Association members fund grants that make connections all over the world.
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 the
baseFieldDefinitions()method, while assigning the
EntityChangedconstraint (excerpt from
$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 the
changedtimestamp via a
Node.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->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->getMessage();