Step 1:
Add hook_install
to custom_module.install
file.
/**
* Implements hook_install().
*/
function custom_module_install() {
$field_storage_definition = BaseFieldDefinition::create('string')
->setLabel(t('Demo field'))
->setDescription(t('The demo field description.'))
->setReadOnly(FALSE)
->setRevisionable(TRUE)
->setTranslatable(TRUE)
->setSettings([
'default_value' => '',
'max_length' => 255,
])
->setDisplayOptions('form', [
'type' => 'string_textfield',
'weight' => 10,
])
->setDisplayConfigurable('view', TRUE)
->setDisplayConfigurable('form', TRUE);
\Drupal::entityDefinitionUpdateManager()
->installFieldStorageDefinition('field_demo_field', 'custom_entity', 'custom_entity', $field_storage_definition);
}
Step 2:
Add hook_entity_base_field_info
to custom_module.module
file.
/**
* Implements hook_entity_base_field_info().
*/
function custom_module_entity_base_field_info(EntityTypeInterface $entity_type) {
$fields = [];
if ($entity_type->id() === 'custom_entity') {
$fields['field_demo_field'] = BaseFieldDefinition::create('string')
->setLabel(t('Demo field'))
->setDescription(t('The demo field description.'))
->setRequired(FALSE)
->setTranslatable(TRUE)
->setSettings([
'default_value' => '',
'max_length' => 255,
])
->setDisplayOptions('form', [
'type' => 'string_textfield',
'weight' => 10,
])
->setDisplayConfigurable('view', TRUE)
->setDisplayConfigurable('form', TRUE);
return $fields;
}
}