protected function AutosaveFormBuilder::restoreAutosavedState in Autosave Form 8
Restores an autosaved form state.
Parameters
$form_id: The form id.
\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.
1 call to AutosaveFormBuilder::restoreAutosavedState()
- AutosaveFormBuilder::rebuildForm in src/
Form/ AutosaveFormBuilder.php - Constructs a new $form from the information in $form_state.
File
- src/
Form/ AutosaveFormBuilder.php, line 173
Class
- AutosaveFormBuilder
- Provides form building and processing with AutosaveForm enabled.
Namespace
Drupal\autosave_form\FormCode
protected function restoreAutosavedState($form_id, FormStateInterface $form_state) {
if (!$form_state
->get('autosave_form_restored') && ($autosaved_timestamp = $form_state
->get('autosave_form_state_timestamp'))) {
$form_object = $form_state
->getFormObject();
// Restore entity form.
if ($form_object instanceof EntityFormInterface) {
$entity = $form_object
->getEntity();
$autosaved_state = $this->autosaveEntityFormStorage
->getEntityAndFormState($form_id, $entity
->getEntityTypeId(), $entity
->id(), $entity
->language()
->getId(), $this
->currentUser()
->id(), NULL, $autosaved_timestamp);
if (is_null($autosaved_state)) {
// @todo Cover the case that the autosaved state has been purged
// meanwhile.
return;
}
/** @var EntityInterface $autosaved_entity */
$autosaved_entity = $autosaved_state['entity'];
/** @var FormStateInterface $autosaved_form_state */
$autosaved_form_state = $autosaved_state['form_state'];
// Restore the form with the entity from the autosaved state.
$form_object
->setEntity($autosaved_entity);
// Restore the user input.
$current_user_input = $form_state
->getUserInput();
$autosaved_user_input = $autosaved_form_state
->getUserInput();
// We have to rebuild the form and keep the generated form token
// instead of putting the one from the autosaved input, otherwise the
// form builder will set an form state error and, which is going to
// result into an exception, as setting form state errors after the
// validation phase is forbidden.
if (isset($current_user_input['form_token'])) {
$autosaved_user_input['form_token'] = $current_user_input['form_token'];
}
$form_state
->setUserInput($autosaved_user_input);
// Recover the form state storage, which is needed to continue from the
// state at which the form was left.
$form_state
->setStorage($autosaved_form_state
->getStorage());
// Flag the form state as being restored from autosave.
$form_state
->set('autosave_form_restored', TRUE);
}
elseif ($form_object instanceof FormInterface) {
// @todo add support for regular forms.
}
}
}