As I talked about in my last post, one of the great things about Drupal 7 is being able to define fields for users, rather than using Content Profile. One of the issues I've seen people come across is saving these custom fields programmatically using Drupal 7. Editing things like the email or roles are basic enough and are well documented, however custom fields have a different structure to the default user fields, and saving them can be slightly different. This bit of code shows how to save a custom field using user_save().

global $user;
 
$account = user_load($user->uid); 

$edit = array(
  'field_favourite_football_team' => array(
    'und' => array(
      0 => array(
        'value' => 'Manchester City',
      ),
    ),
  ),
);
  
user_save($account, $edit);

The problem there is that we've used 'und' as the language. If the set language for that user or the site changes (using the locale module), that piece of code is no longer correct! Here's how to correct it.

global $user;
 
$account = user_load($user->uid); 

$language = ($user->language) ? $user->language : 'und';

$edit = array(
  'field_favourite_football_team' => array(
    $language => array(
      0 => array(
        'value' => 'Manchester City',
      ),
    ),
  ),
);
  
user_save($account, $edit);

Now when you save your user, you'll use the language defined by the user, or set it as undefined. 

Comments

I can see the outputted value on module A but on module B, when i dump or print out that global $user, i cant see that field. Is there anyway to save that on a for global use?

Nice article, worked for me.

Add new comment