Getting through BaseFieldDefinition::create()

Submitted by oioioooi on 10/02/2024 - 17:23

When creating custom entities using the BaseFieldDefinition::create() method in the respective entity class file, one way or another it is required to define the fields the entity should by default contain along with their settings.

The BaseFieldDefinition::create() method expects the field type argument and settings of this field are set using the underlying methods the BaseFieldDefinition class provides.

Two issues that might arise are where from to get the field type value and how set the default field settings.

Getting a clue for the field type

Search for @FieldType annotation in the source code and use the id property for the custom field definition.

field-type-annotation
FieldType annotation

 

An alternative way is to ask the recently popular AI models. I use PhpStorms AI Assistant, but github's Copilot also does the trick.

Making sense out of custom field settings

Now where it gets more serious if defining default field settings. It might be quite obvious with methods like setLabel(), setDefaultValue() whereas it's not with setSetting() and setDisplayOptions().

E.g.:

field-settings-default

As a quick way to get the settings desired, is to click the field in Drupal's UI first and dump it's settings on the screen. These setting can be re-used in the code where the field is defined.

The code below can be placed in various places, where screen output can be achieved. It can be a controller method that returns markup or a form definition.

The dpm() function is available when devel module is enabled.

$fieldName = 'FIELD_MACHINE_NAME';
$fieldDefinitions = \Drupal::service('entity_field.manager')
  ->getFieldDefinitions('ENTITY_TYPE', 'ENTITY_BUNDLE');
if ($fieldDefinitions[$fieldName]) {
  dpm($fieldDefinitions[$fieldName]->getLabel());
  dpm($fieldDefinitions[$fieldName]->getType());
  dpm($fieldDefinitions[$fieldName]->isTranslatable());
  dpm($fieldDefinitions[$fieldName]->isDisplayConfigurable('form'));
  dpm($fieldDefinitions[$fieldName]->isDisplayConfigurable('view'));
  dpm($fieldDefinitions[$fieldName]->getSettings());
  dpm($fieldDefinitions[$fieldName]->getDefaultValueLiteral());
  dpm($fieldDefinitions[$fieldName]->getSetting('allowed_values'));
  dpm($fieldDefinitions[$fieldName]->getSetting('target_type'));
  dpm($fieldDefinitions[$fieldName]->getSetting('handler'));
  dpm($fieldDefinitions[$fieldName]->getSetting('handler_settings'));
  dpm($fieldDefinitions[$fieldName]->getDisplayOptions('form'));
  dpm($fieldDefinitions[$fieldName]->getDisplayOptions('view'));

  $entityFormDisplayService = \Drupal::service('entity_display.repository');
  $entityFormDisplaySettings = $entityFormDisplayService->getFormDisplay('ENTITY_TYPE', 'ENTITY_BUNDLE');
  dpm($entityFormDisplaySettings->toArray()['content'][$fieldName]);
}

Tags