When creating custom entities in Drupal 8, you define a bunch of fields in baseFieldDefinitions() on your entity class, like this:

  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);

    $fields['postal_code'] = BaseFieldDefinition::create('integer')
      ->setDescription(t('Postal code.'))
      ->setSetting('unsigned', TRUE)
      ->setDisplayOptions('form', [
        'type' => 'number',

    return $fields;

However, these fields, despite being marked required, are defined as nullable in the database.

There’s no ->setNullable(FALSE) or similar method on BaseFieldDefinition. So how else do you make Drupal generate the schema correctly?

  • you can always do it in a hook update db_change_field('foo', 'bar','bar', array('type' => 'serial', 'not null' => TRUE)
    – awm
    May 15, 2018 at 20:12

1 Answer 1


There is no API for that at the moment, every field that is specified as a key happens to be set to not null, but that's IMHO actually a bug and I would not rely on that.

Instead, the only thing you can do is provide a storage schema handler and customize the schema there.

See \Drupal\node\NodeStorageSchema::getSharedTableFieldSchema() for example.

  • Ok, thanks, I’ll try to create a coherent bug report based on this.
    – mikl
    May 16, 2018 at 11:27
  • There will be a new method BaseFieldDefinition::setStorageRequired(). As Berdir mentioned there is no API yet but there is work in progress on an API in drupal.org/project/drupal/issues/2841291
    – mpp
    Sep 27, 2018 at 8:40
  • It doesn't appear setStorageRequired() can make a field nullable, as of today.
    – arnoldbird
    Mar 8, 2020 at 19:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.