Quantcast
Channel: Issues for Drupal core
Viewing all articles
Browse latest Browse all 294492

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

$
0
0

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'.


Viewing all articles
Browse latest Browse all 294492

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>