1

can someone tell me why this works

function justatest_form_alter(&$form, $form_state, $form_id) {

  global $user;
  if ( $form_id == 'node_test_form'){
    $form['field_owner']['widget'][0]['value']['#default_value'] = 'test';
  }
  return $form;
}

but this doesn't

function justatest_form_alter(&$form, $form_state, $form_id) {

      global $user;
      if ( $form_id == 'node_test_form'){
        $form['field_owner']['widget'][0]['value']['#default_value'] = $user->uid;
      }
      return $form;
    } 

I'd also like to know how I get the current users name too, if someone can assist with that it would be much appreciated.

  • Please consider adding and accepting your own answer. – leymannx May 5 at 20:21
2

The D8 uid property reference isn't something that can be cast into a string as you could in D7.

In D7, user objects use a generic PHP object class (stdClass) with a uid property containing a string. In D8, user objects use a Drupal\user\Entity\User class. This class does't have a direct uid string property.

In D8 the uid property magically retrieves the User entity field property instead of a simple uid string.

As such, there are other new methods/properties (as you've mentioned) to retrieve the underlying uid value.

0

This worked for me

// Load the current user. 
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id()); 

// retrieve field data from that user 
$name = $user->get('name')->value; 
$uid= $user->get('uid')->value;

Then you can just use

$form['field_owner']['widget'][0]['value']['#default_value'] = $uid;

or

$form['field_owner']['widget'][0]['value']['#default_value'] = $name;

Thanks for looking, if there is a better way then please let me know

Gibbo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy