如何在Drupal 8中创建和保存用户个人资料字段?

时间:2018-07-11 12:39:59

标签: drupal-8

我想通过创建field_first_name添加设置的用户个人资料数据,例如field_profile_first_name而不是用户帐户,我能够像下面给出的那样在用户帐户中设置字段数据,我该如何为个人资料做同样的事情。

 $account = [
        'name' => $user_data->employee_code,
        'pass' => 'password',
        'mail' => $user_data->employee_mail_id,
        'init' => $user_data->employee_mail_id,
        'preferred_admin_langcode' => 'en',
        'timezone' => drupal_get_user_timezone(),
      ];

      $user = User::create($account);
      if (isset($user_data->first_name) && !empty($user_data->first_name)) {
        $user->set("field_first_name", $user_data->first_name);
      }

      if (isset($user_data->last_name) && !empty($user_data->last_name)) {
        $user->set("field_last_name", $user_data->last_name);
      }

      $user->save();

1 个答案:

答案 0 :(得分:0)

首先,创建一个用户,然后创建链接到它的配置文件。例如下面的代码:

  use Drupal\profile\Entity\Profile;
  use Drupal\user\Entity\User;

  $user = User::create();

  // Mandatory.
  $user->setPassword();
  $user->enforceIsNew();
  $user->setEmail($email);
  $user->setUsername($email);

  // Optional.
  $user->set('init', $email);
  $user->set('langcode', $lang);
  $user->set('preferred_langcode', $lang);
  $user->set('preferred_admin_langcode', $lang);
  $user->activate();

  // Save user account.
  $user->save();

  $profile = Profile::create([
    'type' => 'customer',
    'uid' => 1,
    'field_agree_terms' => 1,
    'field_first_name' => $first_name,
    'field_last_name' => $last_name,
  ]);

  $profile->setDefault(TRUE);
  $profile->save();