In the beginning of this chapter, I stressed the importance of understanding the makeup of a field (type, widget, and formatter) for being able to easily define base fields on custom entity types. This understanding allows you to navigate through Drupal core code and discover their settings and use them on base fields. So, let's cement this understanding by seeing how our new field could be defined as a base field on a custom entity type.
Here is an example where we actually use all the available settings we defined for each of the three plugins. Note that any settings that are left out default to the values we specified in the relevant defaults method, as follows:
$fields['plate'] = BaseFieldDefinition::create('license_plate')
->setLabel(t('License plate'))
->setDescription(t('Please provide your license plate number.'))
->setSettings([
'number_max_length' => 255,
'code_max_length' => 5,
'codes' => implode("\r\n", ['NY', 'FL', 'IL']),
])
->setDisplayOptions('view', [
'label' => 'above',
'type' => 'default_license_plate_formatter',
'weight' => 5,
'settings' => [
'concatenated' => 0,
]
])
->setDisplayOptions('form', [
'type' => 'default_license_plate_widget',
'weight' => 5,
'settings' => [
'number_size' => 60,
'code_size' => 5,
'fieldset_state' => 'open',
'placeholder' => [
'number' => '',
'code' => '',
],
]
])
->setDisplayConfigurable('form', TRUE)
->setDisplayConfigurable('view', TRUE);
This is very similar to what we've been seeing. For the create() method, we use the FieldType plugin ID ,and inside the setSettings(), we pass both storage and field settings. They will then be used appropriately. Note that since the codes setting is stored as a string with codes separated by line breaks, we will need to add it accordingly.
Similarly, for the view and form display options, we use the formatter and widget plugin IDs, respectively, and inside a settings array, we pass any of the settings we have defined. Lastly, the setDisplayConfigurable() indicates that all these settings for the formatter and widget are also configurable through the UI. Doing so will turn the BaseFieldDefinition into a BaseFieldOverride, as it needs to store the configured overrides.
This should be a recap for you, as we covered all these concepts in earlier chapters.