0

I have a custom content entity 'service' created with Drupal Console (drupal generate:entity:content).
I added my own fields to the standard ones created by DC. Of which 'seliste_id':

$fields['seliste_id'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('SEListe'))
  ->setSetting('target_type', 'person')
  ->setSetting('handler', 'default');

By default, the code generated by DC handles the owner of any new entity, owner_id being the id of the current user.
By design, seliste_id is the id of the other entity 'person' which is linked 1 <-> 1 to Drupal's 'user'.
So when a new 'service' is created, I'd like to "copy" its owner (i.e. the current user's id) to 'seliste_id'.
I know that I can do that in mymodule_entity_presave().
Is there a way to do that in the definition of 'seliste_id' field?
With ->setDefaultValue() or ->setDefaultValueCallback() maybe?
Any idea?

2 Answers 2

0

From the 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')
  ->setTranslatable(TRUE)
  ->setDisplayOptions('view', [
    'label' => 'hidden',
    'type' => 'author',
    'weight' => 0,
  ])
  ->setDisplayOptions('form', [
    'type' => 'entity_reference_autocomplete',
    'weight' => 5,
    'settings' => [
      'match_operator' => 'CONTAINS',
      'size' => '60',
      'placeholder' => '',
    ],
  ])
  ->setDisplayConfigurable('form', TRUE);

// ...

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

Using the advice (thanks @Berdir), I tried this and it worked!

// ----------------------------------------------------------------------------
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);
// ----------------------------------------------------------------------------
some fields...
// ----------------------------------------------------------------------------
    $fields['seliste_id'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('SEListe'))
      ->setSetting('target_type', 'person')
      ->setSetting('handler', 'default')
      ->setDefaultValueCallback('Drupal\sel\Entity\Service::getCurrentUserId');
// ----------------------------------------------------------------------------
some other fields...
// ----------------------------------------------------------------------------
    return $fields;
  }

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

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.