Normally a default value is configured in the field configuration. Either static in default_value
or dynamic in default_value_callback
pointing to a callback function which returns the default value.
For your original question, how to do this in one of the field plugins, see No way for a field to dynamically set default value and especially #6:
I resorted to creating widgets (extending the base widgets), whose
only concern is to set the default value dynamically according to
contextual values, e.g. I have a widget that presets a default value
to an entity name referenced by the logged in user, something like
this:
/**
* Define the {@link AcmeWidget} class.
*
* @FieldWidget(
* id = "acme_widget",
* label = @Translation("Acme Textfield"),
* field_types = {
* "string"
* }
* )
*
* @package Drupal\acme\Plugin\Field\FieldWidget
*/
class AcmeWidget extends StringTextfieldWidget {
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
// Call our parent but set the value using our default value function.
$element = parent::formElement($items, $delta, $element, $form, $form_state);
// Get the current user organization's name.
$user = User::load(\Drupal::currentUser()->id());
$organization = $user->get('field_organization')->entity->title->value;
// Set the default value if a value hasn't been set.
$element['value']['#default_value'] = $organization;
return $element;
}
}