【问题标题】:drupal user_save() function does not update existing user but create a new onedrupal user_save() 函数不会更新现有用户而是创建一个新用户
【发布时间】:2018-04-04 12:17:22
【问题描述】:

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

// 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;
}

那我该如何解决呢?

【问题讨论】:

标签: php drupal-7 save updates


【解决方案1】:

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 属性的情况。

【讨论】:

  • 感谢您的回答。但它不再工作并且也创建了一个新对象。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-09
    • 1970-01-01
    • 2019-03-12
    • 2021-11-13
    • 1970-01-01
    相关资源
    最近更新 更多