Using #type 'hidden' for hidden inputsfor Drupal 8 , 9 , 10 , and 11

Last updated :  

In this advanced lesson of our Drupal Form API series, we delve into the use of the #type 'hidden' element. Hidden inputs are powerful tools for handling data that does not require user interaction, facilitating background processes or managing state between form submissions. They are often used to store values that should be submitted with the form but not visible or editable by the user directly.

Introduction to #type 'hidden'

The hidden form element in Drupal allows you to store data within a form that the user doesn't see or interact with. This is particularly useful for maintaining state, managing session data, or securely transferring data such as user IDs, session tokens, or flags.

Basic Hidden Input Configuration

Suppose you need to pass a user ID discreetly with a form submission. Here’s how you can configure a basic hidden input:


$form['user_id'] = [
    '#type' => 'hidden',
    '#value' => \Drupal::currentUser()->id(),  // Set a default hidden value, like the current user ID.
];

    

Key Properties Explained

  • #type: Marks the form element as a hidden input, rendering it invisible to the user.
  • #value: Defines the hidden data to be stored, typically set programmatically to hold specific values such as identities or tokens.

Use Cases for Hidden Inputs

Hidden inputs fulfill several important roles in form security and functionality:

Security Tokens

Hidden fields often carry security tokens as part of form submissions to ensure data integrity and guard against cross-site request forgery (CSRF).

Maintaining State

Data can be persisted between form interactions, like keeping track of a session-specific parameter or multi-step form progress hidden from the user.

Pre-Filled Data

Hidden inputs are useful for setting default data that must accompany a submission, such as timestamps or contextual variables defined by the system.

Processing Hidden Inputs in Form Submission

Handling hidden inputs correctly in your form's submission function ensures they interact seamlessly with your data-processing logic:


public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
    $user_id = $form_state->getValue('user_id');
    \Drupal::logger('custom_module')->notice('Form submitted by user ID: @uid', ['@uid' => $user_id]);
    \Drupal::messenger()->addMessage($this->t('Form data processed for user @uid.', ['@uid' => $user_id]));
}

    

In this example, the hidden field value is accessed and logged during the form submission process, demonstrating its invisibility to the user yet full availability to the system.

Best Practices for Using Hidden Inputs

  • Security: Always validate and sanitize any hidden input values to prevent tampering, injection attacks, or accidental disclosure of sensitive data.
  • Confidential Data: Use hidden inputs for passing non-sensitive data; consider encryption for truly sensitive values.
  • Use Sparingly: Overuse of hidden fields may complicate form logic, introducing unnecessary complexity. Keep usage intentional and meaningful.

Conclusion

The #type 'hidden' element in Drupal Form API is a subtle yet powerful tool, enabling non-disruptive data handling and secure information passage within form submissions. By appropriately leveraging hidden inputs, you can enhance the robustness of your forms and improve user experience.

Next Steps

Our next lesson will examine "Using #type 'submit' or #type 'button'", focusing on creating interactive buttons that can trigger form submissions or perform specific client-side actions, integral to form operation and design.