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:
DrupalCoreFormFormBuilderInterface.

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.

5.00 / 5.0
Article rating (0 Reviews)
Do you find this article useful? Please, let us know your opinion and rate the post!
Not badGoodVery GoodGreatAwesome

Do you have a question?

Or do you want to talk and share some news? We’ll be glad to communicate with you and clarify all you need. Feel free to contact us anytime, and we’ll reply as soon as possible. Let’s get acquainted and be partners. We’ll be happy to keep in touch with you.

We accept: DOCX, DOC, ODT, PDF

* - required fields