Skip to content

Instantly share code, notes, and snippets.

@syammohanmp
Created November 8, 2023 08:23
Show Gist options
  • Save syammohanmp/da59f16c96e30a2990e91a9331a541f9 to your computer and use it in GitHub Desktop.
Save syammohanmp/da59f16c96e30a2990e91a9331a541f9 to your computer and use it in GitHub Desktop.
How to add custom field to a custom entity in Drupal.

How to add custom field to a custom entity in Drupal.

Make install file.

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;
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment