2

I have a Drupal 8 installation that has a user reference field and I would like the currently logged in user to be the default value for the field. I believe in Drupal 7 I would've used the [current-user:name] Token for this. That functionality didn't seem to show up when I installed Token for D8.

3
  • What exactly are you entering? Can you check /admin/help/token with the Help module enabled?
    – prkos
    Jun 27, 2019 at 11:18
  • That page does indeed say there is still a [current-user:name] token. However, when I add an Entity Reference field to my content type, my "Default Value" section is only a dropdown of existing users, there is no text field to enter the token listed above. That being said, I could use a Text field, insert the token, but that field would still need to be editable if the value needed to be changed to another user. Now my data could be a username that doesn't exist/is spelled incorrectly/etc.
    – CMarcera
    Jun 27, 2019 at 17:43
  • Entity reference fields only reference IDs, not names. So the correct token should be the one for the current user ID. It seems you need Field default token? Also keep an eye on the issue suggested in that module drupal.org/project/drupal/issues/1070878
    – prkos
    Jun 27, 2019 at 18:27

1 Answer 1

1

You'll probably want to make a utility module and use hook_form_alter() (with a switch statement on the $form_id you're targeting if you're targeting multiple forms) or hook_form_FORM_ID_alter(). Then the following should do the job:

use Drupal\user\Entity\User;
use Drupal\Core\Form\FormStateInterface;

function mymodule_hook_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == "TARGET_FORM_ID") {
    $current_user = \Drupal::currentUser();
    $form['field_user']['widget'][0]['target_id']['#default_value'] = User::load($current_user->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.