In Drupal 7, form validation functions could use either form_set_error() or form_error() to set errors for an element, and form_get_errors() to retrieve the errors for a given form.
These were global functions, which just set or retrieved errors from the current form being processed. This worked fine for form validation functions, but could produce unexpected results when called from non-form functions (like a theme function).
In order to ensure that errors are associated with the correct form, you must now call the form error functions on $form_state.
See also the change notice about the Form Builder class.
Drupal 7
function user_validate_current_pass(&$form, &$form_state) {
// ...
form_set_error('current_pass', t("Your current password is missing or incorrect; it's required to change the %name.", array('%name' => $name)
));
}
Drupal 8
use Drupal\Core\Form\FormStateInterface;
function user_validate_current_pass(&$form, FormStateInterface $form_state) {
// ...
$form_state->setErrorByName('current_pass', t("Your current password is missing or incorrect; it's required to change the %name.", array('%name' => $name)));
}
In addition, there is a new method added for when you want to check if any forms on the page had errors, not any specific one.
Drupal 7
if (form_get_errors()) {
// There were errors, do not continue.
return;
}
Drupal 8
if ($form_state->getErrors()) {
// There were errors, do not continue.
return;
}