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