Problem/Motivation
When creating an integer field as shown in http://drupal.stackexchange.com/questions/188367/how-to-add-uniquefield-... , the UniqueField constraint throws the following error:
The website encountered an unexpected error. Please try again later. TypeError: Argument 1 passed to Drupal\Core\Form\FormState::setError() must be of the type array, null given, called in /var/www/html/web/core/lib/Drupal/Core/Field/WidgetBase.php on line 454 in Drupal\Core\Form\FormState->setError() (line 1156 of core/lib/Drupal/Core/Form/FormState.php).
I could reproduce this bug on core 8.1.7, 8.1.8, 8.2.0-beta1+33-dev (2016-Aug-14) and 8.3.x-dev (2016-Aug-14).
Steps to reproduce:
- Add a custom constraint to a field type number that uses the NumberWidget. This is what the unique_field module does. (https://www.drupal.org/docs/8/api/entity-validation-api/providing-a-cust...)
- Try to create new node that runs the validation.
- The error indicated is thrown.
Proposed resolution
class NumberWidget extends WidgetBase {
// ...
public function errorElement(array $element, ConstraintViolationInterface $violation, array $form, FormStateInterface $form_state) {
if (!empty($element['value'])) {
return $element['value'];
}
return $element[0]['value'];
}
}