Form_state in Drupal 7 and Drupal 8

3 min read

Send to you:

Drupal 7 uses hook form(), form validate(), form submit() hooks for creation, validation, and submission of the form. $form_state array is used for getting values of the filled fields. And today we are going to tell the difference between form_state in Drupal 7 and Drupal 8.

Here is how it works in Drupal 7:

// Get the field value 
echo $form_state['values']['field_id'];
// Get all values of the form
$values = $form_state['values'];

As Drupal 8 is completely based on OOP, the form is an entity here. So, forms are classes (OOP), which are created, implementing an interface:

There are several abstract form classes for different tasks in Drupal 8 core, which you should base on while subclassing:

All data, which the user entered while filling the form, will be in a $form_state variable. But $form_state is an entity in Drupal 8, so you should use the following code to get the necessary field value:

// field_id - name of the form element (a key).
echo $form_state->getValue('field_id');
Use the following method for getting all values:
// Get all form values
$values = $form_state->getValues();

That’s the way it works. We hope it’s helpful for you, but nevertheless, if you need any help, contact us, and we’ll do all necessary work on Drupal development for you.


Article rating (1 Reviews)

Do you find this article useful? Please, let us know your opinion and rate the post!

  • Not bad
  • Good
  • Very Good
  • Great
  • Awesome