0

Whether I'm using User Reference module or Entity Reference module, I can't seem to create a drop-down list of all users, where the current user is selected by default.

So all users will be in the list, but I just want to the default selection to be the current user. How can I do this?

4 Answers 4

2

Using hook_form_alter():

function example_form_alter(&$form, &$form_state, $form_id) {
    global $user;
    if ($form_id === 'my_form') {
        $form['field_user']['#default_value'] = array($user->uid => $user->name);
    }
}

Not tested, but it's the idea.

1
  • I was hoping for a code-less solution, but after searching around it looks like it's just not implemented in either module. Thanks! Mar 6, 2013 at 14:12
0

This is a bit of a stretch, but you could set up a dummy user called 'current user' and set it as the default user for your field. Then, use Rules to target all User entity reference fields (whenever a new node is saved) and change 'current user' to the currently logged in user.

1
  • I like this idea, but it would be nice if "Current User" was actually the person's name. Aside from that, your solution actually sounds like it's worth the stretch. Thanks! Feb 5, 2015 at 3:52
0

If someone is still looking for a programmatic answer, I got the following to work with my code.

$form['field_user']['und']['#default_value'] = (string)$user->uid;

You must cast the $user->uid to a string because this is what the options array is expecting. I am not certain why I had to use the ['und'], but it wouldn't work for me without it. I would try it without the ['und'] if it isn't working for you the way it is.

0

For a user reference autocomplete field, I did the following:

if ($form_id === 'my_node_form') {
  global $user;
  if (empty($form['field_my_field'][LANGUAGE_NONE][0]['uid']['#default_value'])) {
    $form['field_my_field'][LANGUAGE_NONE][0]['uid']['#default_value'] = $user->uid;
  }
}

I tested if the value is empty first, so I don't overwrite an existing value when editing the content.

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.