drupal user_save() 函数不更新现有用户而是创建一个新用户

drupal user_save() function does not update existing user but create a new one

user_save 函数不更新我的用户但抛出异常: SQLSTATE[23000]:违反完整性约束:1062 键 'name' 的重复条目 '' 因为它假设我需要创建一个新的用户对象并且它与另一个对象同名。 我的代码如下:

// load user object
$account = user_load($user->uid);

// update some user property
$saved = $account->selected_keyword;
if(isset($saved))
    array_push($termIds,$saved);
$account->selected_keyword = $termIds;

// save existing user
try {
    user_save((object) array('uid' => $account->uid), (array) $account);
}catch(Exception $e){
    print_r($e);exit;
}

那我该如何解决呢?

user_save() 需要将 $account 作为第一个参数,而不是第二个。您应该为编辑创建一个数组:

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

$edit = array(
  'field_some_custom_field' => array(
    'und' => array(
      0 => array(
        'value' => $new_value,
      ),
    ),
  ),
);

user_save($account, $edit);

你应该适应你的情况 selected_keyword 属性。

我知道我的问题出在 userId,我是通过 drupal_anonymous_user() 函数获取用户 ID,所以 user_save 正在创建一个新用户,但我需要使用它是错误的全球 $user;

我还需要通过 field_create_field() 字段模块的功能创建新字段。