You are here

function conflict_entity_prepare_form in Conflict 8.2

Implements hook_entity_prepare_form().

Loads the original entity into the form for not yet cached entity forms. This is required as forms are not cached on GET, but only on POST requests. Therefore until there was some AJAX interactions with the form it will remain uncached. However if the form was submitted with changes without being cached before and in the meanwhile the entity has been saved in another session then the currently rebuilt form for submitting it will be using the newer version of the entity instead of the one used for generating it. For proper conflict handling we however need that the form is built with the originally used entity.

Note: when the referenced drupal.org issue is solved we would not need to store the entity in the key value store anymore and exchange it in the form.

See also

https://www.drupal.org/project/drupal/issues/2824293

File

./conflict.module, line 109
The module that makes concurrent editing possible.

Code

function conflict_entity_prepare_form(EntityInterface $entity, $operation, FormStateInterface $form_state) {
  if (!$entity
    ->isNew() && !$form_state
    ->isCached()) {
    $conflict_entity_original_hash = $form_state
      ->getUserInput()['conflict_entity_original_hash'] ?? NULL;
    if ($conflict_entity_original_hash) {
      $original_entity = \Drupal::keyValueExpirable('conflict_original_entity')
        ->get($conflict_entity_original_hash);
      if ($original_entity) {
        $original_entity = unserialize($original_entity);

        /** @var \Drupal\Core\Entity\EntityFormInterface $form_object */
        $form_object = $form_state
          ->getFormObject();
        $form_object
          ->setEntity($original_entity);
        $form_state
          ->set('conflict-exchanged-entity', TRUE);
      }
    }
  }
}