I am attempting to create a new Drupal 7 user and then assign the UID of that user to a variable. I want to store this UID so that I can create a new node and assign that user as the owner.
QUESTION: Does anyone know how to get the UID of the newly created user?
MY CODE:
// CREATE USER
$newUser = array(
'name' => $refereeUsername,
'pass' => $refereePassword,
'mail' => $refereeEmail,
'status' => 1,
'init' => $refereeEmail,
'roles' => array(
2 => 'authenticated',
53 => 'Referer',
),
);
user_save($usera, $newUser);
// MY ATTEMPT TO GET THE NEWLY CREATED USER ID
$uidn = $usera->uid;
// CREATE NODE
$node = new stdClass;
$node->type = 'referee';
$node->title = 'Referee report for xx';
$node->uid = $uidn;
$node->status = FALSE;
$node->field_testff['und'][0]['value'] = "testworked";
node_object_prepare($node);
node_save($node);
user_save() returns the user object upon successful save (the variable is sent by value, not by reference). Try this:
$account = user_save($newUser);
$uidn = $account->uid;
To solve this issue I used the user_load_by_mail() function. Using the user_save() function caused an integrity constraint violation error in my code.
$accountb = user_load_by_mail($email);
$uidn = $accountb->uid;
Documentation:
https://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_load_by_mail/7
Related
I'm trying to pull the last inserted id from a database table so that I can input it into a new database table, like so:
$mealplaninput =
MealPlanInput::create([
'meal_type' => $meal,
'suitable_for' => $suited,
'allergens' => $allerg,
'specific_allergen' => $spec,
'no_of_people' => $nop,
'start_date' => $request->date,
'no_of_days' => $nod,
'user_id' => $currentuserid,
]);
The attempt to pull the last id (but doesn't work):
$uniquemealplanid = $mealplaninput->id();
To then input into new table:
MealPlanDisplay::create([
'MealPlan_ID' => $uniquemealplanid,
'Day' => $recipeday,
]);
However I get the error:
Call to undefined method App\Models\MealPlanInput::id()
I have tried other methods too, like:
$uniquemealplanid = $this->create($mealplaninput)->id;
But the error I get is:
Method App\Http\Controllers\MealPlanInputController::create does not exist.
How can I pull the last id from MealPlanInput?
You need to create an object from the model to get ID.
$mealplaninput = new MealPlanInput;
$mealplaninput->meal_type = $meal;
$mealplaninput->suitable_for = $suited;
$mealplaninput->allergens = $allerg;
$mealplaninput->specific_allergen = $spec;
$mealplaninput->no_of_people = $nop;
$mealplaninput->start_date = $request->date;
$mealplaninput->no_of_days = $nod;
$mealplaninput->user_id = $currentuserid;
$mealplaninput->save();
$uniquemealplanid = $mealplaninput->id;
you need to try
$uniquemealplanid = $mealplaninput->id;
insted of
$uniquemealplanid = $mealplaninput->id();
while I am updating record it display above error.
message id seems like this - 1536126282209770000
$q = new CDbCriteria(array(
'condition' => 'tokenId = :btokenid',
'params' => array(
':btokenid' => $tokenId,
),
));
$record = self::model()->find($q);
$record->messageId = $messageId;
if (!$record->save()) {
$_errors = current($record->getErrors());
throw new Exception($_errors[0]);
}
I added 2 primary keys for table.
table structure:
After adding primary keys to table need to flush the cache
To refresh the database cache :
Load all tables of the application in the schema
Yii::app()->db->schema->getTables();
clear the cache of all loaded tables
Yii::app()->db->schema->refresh();
If you want to refresh only one table, you can also do :
Yii::app()->db->schema->getTable('tablename', true);
After that It works fine.
user_save function does not update my user but throw exception :
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'name'
because it suppose I need to make a new user object and it has the same name of the other.
my code is in follow:
// 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;
}
so how can I fix it?
user_save() needs to have $account as first argument, not as second. You should create an array for the edits:
$account = user_load($user->uid);
$edit = array(
'field_some_custom_field' => array(
'und' => array(
0 => array(
'value' => $new_value,
),
),
),
);
user_save($account, $edit);
You should adapt to your case for the selected_keyword property.
I understood my problem was with userId, I was getting the user Id by drupal_anonymous_user() function so the user_save was creating a new user and it was wrong I needed to use global $user;
Also I needed to create new field by field_create_field() function of field module.
I recently upgraded fom php 5.2 to 5.6 and there is some code I could not fix yet:
//Finds users with the same ip- or email-address
function find_related_users($user_id) {
global $pdo;
//print_R($pdo);
//Let SQL do the magic!
$sth = $pdo->prepare('CALL find_related_users(?)');
$sth->execute(array($user_id));
//print_R($sth);
//Contains references to all users by id, to check if a user has already been processed
$users_by_id = array();
//Contains arrays of references to users by depth
$users_by_depth = array();
while ($row = $sth->fetchObject()) {
//Create array for current depth, if not present
if (!isset($users_by_depth[$row->depth]))
$users_by_depth[$row->depth] = array();
//If the user is new
if (!isset($users_by_id[$row->id])) {
//Create user array
$user = array(
'id' => $row->id,
'name' => $row->name,
'email' => $row->email,
'depth' => $row->depth,
'adverts' => array()
);
//Add all users to depth array
#array_push($users_by_depth[$row->depth], &$user);
//Add references to all users to id array (necessary to check if the id has already been processed)
$users_by_id[$row->id] = &$user;
}
//If user already exists
else
$user = &$users_by_id[$row->id];
//Add advert to user
if ($row->advert_id != null)
array_push($user['adverts'], array(
'id' => $row->advert_id,
'title' => $row->advert_title,
'msgs' => $row->msgs,
'url' => $row->url
));
#print_r($user);
//Unset $user variable !!!
//If this is missing, all references in the array point to the same user
unset($user);
}
//Return users, grouped by depth
return $users_by_depth;
}
If I simply remove the ampersand before the dollar sign, the function stops to work as intended. From other questions on stackoverflow I found that this is a call by reference and will brake for new php versions. However I could not find a solution yet.
Thank you for any help on how to update this code for php 5.6.x
Your code was probably never working as you thought it was as you are suppressing the errors on your array_push() call. Note that only the first parameter of array_push() is passed by reference, the other values are always passed by value.
You should remove the error suppressor # (never use that in your own code) and in this case you can also do:
$users_by_depth[$row->depth][] = &$user;
^^ add an element just like `array_push`
Now your new value in your $users_by_depth will contain a reference to the $user variable.
I'm trying to create 10 new rows in controller if the userid is not found in the user_id row. I tried create() function and then save() function but it doesn't seem to do the job.
Below is the code, is there a way we can solve this issue?
function invite_fellows(){
//Read userid
$userid = $this->Session->read('Auth.User.id');
$invite_table = $this->User->Invite->findbyUserId($userid);
if(empty($invite_table)){
$code_limit = 10;
//Save 10 unique codes for the user
for($i=0; $i<$code_limit;$i++){
$unique_id = $this->_unique($userid); // Unique id with userid as initial prefix
$this->data['Invite'] = array('user_id' => $userid, 'code' => $unique_id);
$this->User->Invite->create();
$this->User->Invite->save($this->data['Invite']);
}
}
//Find user in users and associated tables
$user = $this->User->findbyId($userid);
//Find user in invite table
$confirmed = $this->User->Invite->find('count', array('conditions' => array('user_id' => $userid,'invited_user >' => 0)));
$this->set(compact('user','confirmed'));
}
Thank you.
Most likely there's a validation rule that blocks the save. Try adding debug( $this->User->Invite->validationErrors ); after the save() to check for that. Make sure debug level is set to at least 1 in core.php.