Submit function to save field values per entity create/edit action.

1 string reference to 'autofill_fields_submit'
autofill_fields_form_alter in ./autofill_fields.module
Implements hook_form_alter().

File

./autofill_fields.module, line 129

Code

function autofill_fields_submit($form, FormStateInterface $form_state) {
    if (!($user_id = \Drupal::currentUser()->id())) {
        return;
    }
    // Ensure that the form entity is properly loaded.
    if (!($entity = $form_state->getFormObject()
        ->getEntity())) {
        return;
    }
    
    //TODO: get real form mode.
    $form_mode = 'default';
    $entity_form_display = EntityFormDisplay::load($entity->getEntityTypeId() . '.' . $entity->getType() . '.' . $form_mode);
    foreach ($entity_form_display->getComponents() as $name => $component) {
        if (empty($component['third_party_settings']['autofill_fields']['autofill'])) {
            continue;
        }
        if (!isset($component['third_party_settings']['autofill_fields']['stored'])) {
            $component['third_party_settings']['autofill_fields']['stored'] = [];
        }
        $component['third_party_settings']['autofill_fields']['stored'][$user_id] = $form_state->getValue($name);
        if ($component['type'] == 'datetime_default') {
            $value = $form_state->getValue($name)[0]['value']
                ->format('c');
        }
        else {
            $value = $form_state->getValue($name);
        }
        $component['third_party_settings']['autofill_fields']['stored'][$user_id] = $value;
        $entity_form_display->setComponent($name, $component);
    }
    $entity_form_display->save();
}