It can be useful to define custom entities programatically for streamlined CRUD webapps using Drupal. One nice thing about doing it this way is that you can keep all your entity definitions in the code, so deployment is easier - no clicking around on the various environments to keep things synced or akward db sync scripts.

Sometimes a custom entity needs to have a hidden field that should not be exposed in the user-facing create/edit form. It might have a value that’s handled programatically, like a timestamp for when the entity was published, or in my case, a special kind of “owner” that differs from the entity creator.

I couldn’t find any documentation on how to do this, and had to dig through core to find the answer, so I thought I’d share.

The trick is in the field’s definition, for the form display options, set the field’s region to hidden

->setDisplayOptions('form', [
    'region' => 'hidden',
  ]);

In a little more detail .. in your entity’s definition:


// ... snip

class MyCustomEntity extends ContentEntityBase {
  // ... snip
}

you define the entity fields in the baseFieldDefinitions method:

public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {

  // the owner of the thing
  $fields['owner_id'] = BaseFieldDefinition::create('entity_reference')
    ->setSetting('target_type', 'user')
    ->setSetting('handler', 'default')
    ->setDisplayOptions('form', [
      'region' => 'hidden',
    ]);

}

As usual, flush the cache and it should now be hidden!