Skip to main content

Drupal 8: How to tell if a form is empty or has not been submitted yet

This is how you can tell if this is the first time a form is rendered with empty submitted data.

/**
 * Add message to show that is the default rendered form
 *
 * Implements hook_form_alter().
 */
function hook_form_alter(array $form, FormStateInterface $form_state) {
  // Check if this is the initial load of the form.
  if (empty($form_state->getUserInput()) {
    // Do stuff on node create form initial load.
    \Drupal::messenger()->addMessage(t('This is form has not been submitted before'), 'info');
  }
  else {
   //How to get previously submitted data
   $userInputData = $form_state->getUserInput();
   $custom_field_default_Value = isset($userInputData['custom_Field']) ? $userInputData['custom_Field'] : null;
 }
}

 

hook_form_alter form api

Latest Articles

VSCode Drupal Coding Standards Setup (From Scratch) admin_pixelthi… Mon, 12/22/2025 - 16:01 VSCode Drupal Coding Standards Setup (From Scratch)

VSCode Drupal Coding Standards Setup (From Scratch)

vscode
Using drupal/core-composer-scaffold to prevent rewriting .htaccess or robots.txt file admin_pixelthi… Sun, 12/01/2024 - 16:49 Using drupal/core-composer-scaffold to prevent rewriting .htaccess or robots.txt file

Using drupal/core-composer-scaffold to prevent rewriting .htaccess or robots.txt file

composer
Controlling ckeditor styling options with hook_editor_js_settings_alter admin_pixelthi… Thu, 05/16/2024 - 10:49 Controlling ckeditor styling options with hook_editor_js_settings_alter

Controlling ckeditor styling options with hook_editor_js_settings_alter

php hook hook_editor_js_settings_alter hook_field_widget_single_[WIDGET_TYPE]_form_alter