Save user profile on Drupal

Tested on:

  • Drupal 5.x

After you have created some user fields through Profile module provided by core, you can have the need to save value into the user object. Here a quick howto to do this.

On user creation:

/** create user profile ($new_user will be an user object) */
$new_user_array = array (
  'name' => "funnyusername",
  'pass' => "MyVerySecurePassword",
  'mail' => "info@example.gom",
  'status' => 1, # status: active
);
$new_user = user_save(NULL, $new_user_array, $category = 'account');
/** assign values to profile fields */
$new_user_edit =  array(
'profile_surname' => "Yumemiya",
'profile_name' => "Arika",
);
/** create and save profile fields */
profile_save_profile($new_user_edit, $new_user, "Character ID");

Where “Character ID” is the category name for profile_surname e profile_name.

To load current user instead creating new one, you have to use

global $user;

instead a previously declared user object $new_user.

See also:

Update:

  • Using this method during a cronjob (using hook_cron) I experienced an error: profile values are passed, but not written, but only if cronjob is launched automatically, and not forced by Report screen (as admin). After some days, I discovered that it’s a permission issue.
    Problem:
    Add a “cronbot” user with some privileges over user (“administer user”) to allow writing even on hidden Profile field.
    Solution:
    On a dedicated server, with a dedicated IP, you can automatically login by IP (by IP Login module for 5.x and 6.x) the cronjob using the server IP or loopback address (127.0.0.1) depending on server configuration (I use the first in production, the latter on local testing).

    1. Add an ip_login Profile field (single line text field, hidden field)
    2. Enable IP Login module
    3. Assign ip_login field to IP login by IP Login configuration screen
    4. Create a new role named “cronbots”, with “administer users” permission.
    5. Create a new user named “cronbot”, with “cronbots” role assigned
    6. Change the “IP login” field for “cronbot” to your server IP (127.0.0.1 or your static IP address as listed on ifconfig on *nix servers)

    On the next automatic cron run (not force it), you’ll see the “cronbot” user logging in. On Drupal logs, the cronjob execution pass from “Anonymous” to “cronbot”, and profile fields are rightly written.
    The other way:
    Just write profile field via db_query. (You don’t want to do a weird thing like that, right? 😉 )

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s