Snippet: How to programmatically create a user using entity API

Roman Zimmermann's picture
Roman Zimmermann

There seems to be a lot of documentation around on how to create new entity types. Sadly I couldn't find a description on how to actually create entities. Here's how it worked for me.

This code creates a new user and adds content for two fields in it's main profile.


$newUser = entity_create('user', array());
$newUser->name = $email;
$newUser->mail = $email;
$newUser->status = 1;
entity_save('user', $newUser);

$main_profile = entity_create('profile2', array('type' => 'main'));
$main_profile->uid = $newUser->uid;
$main_profile->field_first_name[LANGUAGE_NONE][0]['value'] = $first_name;
$main_profile->field_last_name [LANGUAGE_NONE][0]['value'] = $last_name;
$main_profile->save();

$newUser->profiles['main'] = $main_profile;
return $newUser;

The API seems to be a lot less homogeneous than I'd expected. In this case entity_create('user', …) returns a standard class whereas entity_create('profile2', …) returns an object that implements the Entity API.

 

EDIT: thanks for the correction.

Comments

$main_profile->field_first_name[LANGUAGE_NONE][0]['value'] = $first_name;
$main_profile->field_last_name [LANGUAGE_NONE][0]['value'] = $last_name;

Pages

Add new comment