formstateInterface

What is FormStateInterface in Drupal?

  • Profile picture of Mcs
  • by Mcs July 1, 2025

n Drupal, the FormInterface is a contract that defines what methods a form class must implement to be considered a valid form. It's part of Drupal's Form API system, and it ensures consistency across different kinds of forms (e.g., configuration forms, entity forms, simple custom forms).

What is FormStateInterface?

FormStateInterface is an object that holds all the data about a form during its build, validation, and submission phases. It acts like a container that stores:

  • User input (what someone typed in a form)
  • Error messages
  • Temporary values
  • Information about which button was clicked
  • Internal flags (e.g. whether the form is rebuilt)

Why is FormStateInterface important?

It's how Drupal tracks and processes form data without relying on raw $_POST values. It gives you a clean, safe, and Drupal-friendly way to interact with form input and behavior.

Commonly Used Methods

MethodDescriptionExample
$form_state->getValue('field_name')Get a single field's submitted value$name = $form_state->getValue('name');
$form_state->setValue('field', 'value')Set a value programmatically$form_state->setValue('email', 'example@site.com');
$form_state->getValues()Get all submitted values as an array$values = $form_state->getValues();
$form_state->setErrorByName('field', 'Message')Add a validation error for a field$form_state->setErrorByName('email', 'Invalid email');
$form_state->setRebuild(TRUE)Force the form to rebuild (useful in AJAX or wizard-style forms) 
$form_state->isSubmitted()Check if form was submitted 

Example in Context

 

public function submitForm(array &$form, FormStateInterface $form_state) {
 $name = $form_state->getValue('name');
 $email = $form_state->getValue('email');

 \Drupal::messenger()->addMessage("Name: $name, Email: $email");
}

This is how you'd read the submitted values from the form and do something with them, like show a message or save to the database.

Think of it like this:

$form = blueprint of the form (HTML structure)

$form_state = live data and behavior about how the user interacted with the form

Comments

Add new comment

Restricted HTML

  • Allowed HTML tags: <br> <p> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id> <cite> <dl> <dt> <dd> <a hreflang href> <blockquote cite> <ul type> <ol type start> <strong> <em> <code> <li>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.