The title basically says it all. I have the following field definition in an Entity class:
$fields['code'] = BaseFieldDefinition::create('integer')
->setLabel(t('unique code'))
->setDescription(t('Some unique code'))
->addConstraint('UniqueField')
->setTranslatable(false)
->setRequired(true)
->setDisplayOptions('view', array(
'label' => 'above',
'weight' => 4,
))
->setDisplayOptions('form', array(
'weight' => 4,
))
->setDisplayConfigurable('form', true)
->setDisplayConfigurable('view', true);
Creating a new entity in the UI works as expected as long as I do not set the code value to something already in the database. However, as soon as I try to create a new entity with an already existing value for code (thus triggering a constraint violation), I get 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).
If I change the field definition to use a string instead everything works as expected:
$fields['code'] = BaseFieldDefinition::create('string')
->setLabel(t('unique code'))
->setDescription(t('Some unique code'))
->setSetting('max_length', 5)
->addConstraint('UniqueField')
->setTranslatable(false)
->setRequired(true)
->setDisplayOptions('view', array(
'label' => 'above',
'weight' => 4,
))
->setDisplayOptions('form', array(
'weight' => 4,
))
->setDisplayConfigurable('form', true)
->setDisplayConfigurable('view', true);
So the question is how do I add a unique constraint for an integer field? Is there another validation class I can use, am I setting up my integer field definition wrong thus causing the error, or?
Recoverable fatal error: Argument 1 passed to Drupal\Core\Form\FormState::setError() must be of the type array, null given
. I am on Drupal v8.1.7