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?

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.

|improve this answer|||||
  • I was hoping for a code-less solution, but after searching around it looks like it's just not implemented in either module. Thanks! – Johnathan Elmore Mar 6 '13 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.

|improve this answer|||||
  • 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! – Johnathan Elmore Feb 5 '15 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.

|improve this answer|||||
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.

|improve this answer|||||

Your Answer

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

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