allow FieldConfigInterface::setDefaultValueCallback() to accept a callback in service notation

Created on 26 May 2018, over 6 years ago
Updated 19 October 2023, 12 months ago

FieldConfigInterface::setDefaultValueCallback() accepts a callback for a base of config field's default value, either as a function or method name.

We get this pattern repeated by entity types over and over again for fields where the default value comes from a service, such as the uid and created fields:

Node entity:

    $fields['uid'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Authored by'))
      ->setDescription(t('The username of the content author.'))
      ->setRevisionable(TRUE)
      ->setSetting('target_type', 'user')
      ->setDefaultValueCallback('Drupal\node\Entity\Node::getCurrentUserId')

...

  public static function getCurrentUserId() {
    return [\Drupal::currentUser()->id()];
  }

Media entity:

    $fields['uid'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Authored by'))
      ->setDescription(t('The user ID of the author.'))
      ->setRevisionable(TRUE)
      ->setDefaultValueCallback(static::class . '::getCurrentUserId')
...

    $fields['created'] = BaseFieldDefinition::create('created')
      ->setLabel(t('Authored on'))
      ->setDescription(t('The time the media item was created.'))
      ->setTranslatable(TRUE)
      ->setRevisionable(TRUE)
      ->setDefaultValueCallback(static::class . '::getRequestTime')

...

  public static function getCurrentUserId() {
    return [\Drupal::currentUser()->id()];
  }

  public static function getRequestTime() {
    return \Drupal::time()->getRequestTime();
  }

We could remove these wrapper method and save on repeated code and improve DX if we allow setDefaultValueCallback() to accept a callback in service notation the same way that route controllers do, that is, 'service_name:method'.

Feature request
Status

Needs work

Version

11.0 🔥

Component
Field 

Last updated about 14 hours ago

Created by

🇬🇧United Kingdom joachim

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024