6

I'm trying add a new user to drupal 7, here is my code:

$values = array('name' => $name, 'pass' => $password,  'mail' => $email, 'status'=>1);
$newUser = user_save('', $values);

But i also have the new field field_foobar, if i add it to the values array drupal does nothing with it. What is the correct drupal way of adding these values to my user object so that drupal saves them when i call the user_save function?

I also saw that the fields are stored in the same type of table that stores custom fields of nodes. Also can't get this done, but i guess these 2 problems can have the same solution.

Thanks!

8

I haven't done this with user_save() before but if it follows convention from the rest of the system (which is likely) it'll be like this:

$values = array(
  'name' => $name, 
  'pass' => $password,  
  'mail' => $email, 
  'status'=>1,
  'field_foobar' => array(
    LANGUAGE_NONE => array(
      0 => array(
        'value' => $field_value
      )
    )
  )
);

$newUser = user_save('', $values);

In fact there are a few examples further down the page in the user_save() docs confirming this method is the right one.

  • Thanks this works. I've done it this way except for the LANGUAGE_NONE array. That's why it didn't work.. – jivanrij Aug 15 '12 at 9:40
  • Thanks, this answer pointed me in the right direction to save a new field I added to commerce orders. – Quentin Skousen Mar 29 '16 at 15:26
0

Take a look at an existing user that has all the fields filled in.

For example. Add the following to your code somewhere:

global $user;
dpm($user);

When you know what the user object looks like, it's easy to duplicate the fields in it.

Also take a look at this page, describing how to add users programatically.

0

In my case, I had to UPDATE the user account. So, I read Clive's answer which is specifically for ADDing a user account. Later, I started to review the user_save function sourcecode, and an online discussion on this topic, and found the following lines of code working:

$loaded_user = user_load($uid); //$uid is a variable with the user id numeric value
$updated_values = array(
  'field_first_name' => array(
    LANGUAGE_NONE => array(
      0 => array(
        'value' => "ehsan"
      )
    )
  )
);
$loaded_user->is_new = 0;
$loaded_user->original = entity_load_unchanged('user', $uid);
$newUser = user_save($loaded_user, $updated_values);

So the $updated_values are the updated fields which if your are really like to address them with the correct structure, use the following lines before writing the above lines of code:

$test_user = user_load($uid);
dpm($test_user);

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.