Drupal 7 - Create a user with custom fields based on Taxonomy terms

Submitted by n8coder on Sat, 04/11/2015 - 13:14

Let say we have a travel-website. Each user has fields like :
- My Hometown (single entry)
- Visited cities (multiple entries)
- Cities I want to visit (multiple entries)

And we want to restore user-db from an extern-file. We have to prepare taxonomy terms and assign IDs before starting insert data. After parsing data, we can create each user with following php-code.

$uname = "Alex Miller";
$umail = "alex.miller@example.com";

$hometown_id = 123;
$visited_city1 = 345;
$visited_city2 = 456;

$tovisit_city1 = 678;
$tovisit_city2 = 789;

$new_user = array(
'name' => $uname,
'pass' => 'Password',
'mail' => $umail,
'status' => 0,
'timezone' => 'Europe/Paris',
'init' => $umail,
'field_hometown' =>
array(
'und' =>
array( 0 =>
array('tid' => $hometown_id )
)
),

'field_visited_cities' =>
array(
'und' =>
array( 0 => array('tid' => $visited_city1 ) ,
                   1 => array('tid' => $visited_city2 )
)
),

'field_to_visit_cities' =>
array(
'und' =>
array( 0 => array('tid' => $tovisit_city1 ) ,
                   1 => array('tid' => $tovisit_city2) )
)
)

);

if ( !db_query("SELECT COUNT(*) FROM {users} WHERE name = :name", array(':name' => $uname) ) -> fetchField() ) {
  // User doesn't exist
   $new_drupal_user = user_save(NULL, $new_user);
}

Add new comment