Form_state in Drupal 7 and Drupal 8

form_state in Drupal

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.

Do you have a question?

Or do you want to talk with us and share any news? We would be glad to speak with you and clarify anything you’d like to learn more about. Feel free to contact us at any time, and we’ll reply as soon as possible. Let’s get acquainted and be partners. We’d love to hear from you.

We accept: DOCX, DOC, ODT, PDF