function autosave_form_form_alter in Autosave Form 8
Implements hook_form_alter().
File
- ./
autosave_form.module, line 36 - This module holds autosave form functionality.
Code
function autosave_form_form_alter(&$form, FormStateInterface $form_state, $form_id) {
$active_on = \Drupal::configFactory()
->get('autosave_form.settings')
->get('active_on');
$form_object = $form_state
->getFormObject();
if ($form_object instanceof ContentEntityFormInterface) {
if (!$active_on['content_entity_forms']) {
return;
}
$entity = $form_object
->getEntity();
$entity_type_id = $entity
->getEntityTypeId();
$allowed_content_entity_types = \Drupal::configFactory()
->get('autosave_form.settings')
->get('allowed_content_entity_types');
// Autosave is enabled if either no restriction has been made or the current
// entity type is part of the restriction and as well either no restriction
// on bundle level has been made or the current bundle is part of that
// restriction.
if (!empty($allowed_content_entity_types)) {
if (!isset($allowed_content_entity_types[$entity_type_id]) || !empty($allowed_content_entity_types[$entity_type_id]['bundles']) && !isset($allowed_content_entity_types[$entity_type_id]['bundles'][$entity
->bundle()])) {
return;
}
}
}
elseif ($form_object instanceof EntityFormInterface) {
if (!$active_on['config_entity_forms']) {
return;
}
}
else {
return;
}
// Allow autosave only for entity form routes, as forms might be included in
// blocks and other places and it is impossible to determine to which URL we
// have to post the autosave submit to. Also we don't support embedded forms
// as e.g. it might be surprising for the user getting autosave on the entity
// view, because e.g. a block is using an entity form.
$route = \Drupal::routeMatch()
->getRouteObject();
if ($route && ($route_defaults = $route
->getDefaults()) && isset($route_defaults['_entity_form'])) {
list($entity_type_id, $form_op) = explode('.', $route_defaults['_entity_form']);
$entity = $form_object
->getEntity();
if ($entity
->getEntityTypeId() != $entity_type_id || $form_object
->getOperation() != $form_op) {
return;
}
}
else {
return;
}
$entity_type_manager = \Drupal::entityTypeManager();
if ($entity_type_manager
->hasHandler($entity
->getEntityTypeId(), 'autosave_form')) {
$autosave_form_handler = $entity_type_manager
->getHandler($entity
->getEntityTypeId(), 'autosave_form');
if ($autosave_form_handler instanceof AutosaveEntityFormHandlerInterface) {
$autosave_form_handler
->formAlter($form, $form_state);
}
}
}