Skip to content

Instantly share code, notes, and snippets.

@MatthieuScarset
Last active August 28, 2024 05:51
Show Gist options
  • Save MatthieuScarset/4fe8fe8c5b92b21093cf4b3c4ee766c8 to your computer and use it in GitHub Desktop.
Save MatthieuScarset/4fe8fe8c5b92b21093cf4b3c4ee766c8 to your computer and use it in GitHub Desktop.
Drupal 8 - Programatically create new fields
<?php
/**
* Implements hook_entity_base_field_info().
*/
function mymodule_entity_base_field_info(EntityTypeInterface $entity_type) {
if ($entity_type->id() == 'user') {
$fields = [];
$default_field_definition = [
'type' => 'string',
'label' => t('My application field'),
'description' => NULL,
'displays' => [
'form' => FALSE,
'view' => TRUE,
],
'settings' => [
'max_length' => 255,
],
'read-only' => TRUE,
];
$custom_fields_definitions = [
'account_id' => [
'label' => t('My application account ID'),
'description' => t('The unique ID on My application.'),
'settings' => ['max_length' => 60],
'constraints' => ['UniqueField'],
],
'account_name' => [
'label' => t('My application account name'),
'description' => t('The account name on My application.'),
'settings' => [
'max_length' => 60,
'case_sensitive' => TRUE,
],
'constraints' => ['UniqueField'],
],
'username' => [
'label' => t('My application username'),
'description' => t('The account name on My application.'),
'settings' => [
'max_length' => 60,
'case_sensitive' => TRUE,
],
'constraints' => ['UniqueField'],
],
'email' => [
'type' => 'email',
'label' => t('My application account email'),
'description' => t('The email on My application.'),
],
'first_name' => [
'label' => t('First name'),
'description' => t('The first name from My application.'),
],
'last_name' => [
'label' => t('Last name'),
'description' => t('The last name from My application.'),
],
'score' => [
'type' => 'integer',
'label' => t('My application score'),
'description' => t('Number of votes for this user on My application.'),
'settings' => ['unsigned' => TRUE],
],
'is_pro' => [
'type' => 'boolean',
'label' => t('Pro enabled'),
],
];
$myapp_fields = [];
foreach ($custom_fields_definitions as $name => $field) {
$myapp_fields['myapp_' . $name] = $field + $default_field_definition;
}
foreach ($myapp_fields as $field_name => $field_info) {
$field_definition = BaseFieldDefinition::create($field_info['type'])
->setLabel($field_info['label'])
->setDescription($field_info['description'])
->setReadOnly($field_info['read-only']);
foreach (($field_info['displays'] ?? []) as $key => $value) {
$field_definition->setDisplayConfigurable($key, $value);
}
foreach (($field_info['settings'] ?? []) as $key => $value) {
$field_definition->setSetting($key, $value);
}
foreach (($field_info['constraints'] ?? []) as $constraint) {
$field_definition->addConstraint($constraint);
}
$fields[$field_name] = $field_definition;
}
return $fields;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment