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:
- ConfigFormBase – for creating the forms with settings;
- ConfirmFormBase – a form for the confirmation;
- FormBase – the base class for all other form types.
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.