Hi there,
I recently spent an hour researching how to create a default value for a user reference field. I wanted to create a work history for my users which they would fill in themselves. Obviously, the work history needed to reference to the user filling in the form. For the work history content type I had created a user reference field and I was having difficulty working out how to automatically fill it in with the name of the user.
There seemed to be three approaches:
1. Use a PHP snippet in the default value field for the content type.
2. Use the Prepopulate module.
3. Use hook_form_alter.
The first option was not available to me because I'm using Drupal 7, and Drupal 7, as far as I know, doesn't allow PHP snippets in the default value field for fields unlike Drupal 6.
The second option is helpfully outlined at CCK user reference auto complete by Radiating Gnome and also by N1ckhead at User Reference.
The third option I was a little reluctant to do because I'm not a natural PHP programmer, and it always takes a fair amount of trial and error to get it right, though there are many good examples of how to do this, for example at Drupal CCK Date: how to set datetime field's default value to a fix date?.
I thought these were my only options until I came across the post at Drupal 7, Default value php snippet missing?. There, P4tient, intelligently asked why it was necessary to have a default value for a user reference field when there already is the author field for all Drupal nodes. I had totally overlooked the author field. This completely eliminates the need for the user reference field as the author field can be used in views and anywhere else it is needed for my purposes. So many thanks to P4tient for pointing this out. I also suspect there are many others coming across the same problem and missing this obvious answer. Sometimes it is easy to miss the wood for the trees, or is it the other way around?
Anyway, I hope this post help some other people with a similar problem. Also, maybe some of the guys at Drupal would consider allowing PHP snippets back in the default value fields...
Edit:
I forgot to mention the reason I was also reluctant to use option 2 was because there was only a dev release for this module.
Comments
Default value with other options?
I'm not sure if I'm following this entirely. I would like to have a default selected for a User Reference, but not have that as the only option. On my site, I'd like parent users to add child entities, with their uid as the default for the Parent user reference. However, there will be times when other users may be adding child entities for different parent users or for parents that aren't users yet. Any way to have a default selected but not have it be the only choice?