How can I load user object by email address in Drupal 7? - drupal-7

Been searching furiously on Google and the Drupal docs for something equivalent to function user_load for D6 as used here.
The user_load function in D7 takes a UID while the D6 version is flexible enough to allow email addresses.
Any clues how I can achieve the same end in D7?
Thanks

... or you could just use user_load_by_mail: http://api.drupal.org/api/drupal/modules--user--user.module/function/user_load_by_mail/7

Got the answer on Drupal forums. Basically involves loading user Id associated with email directly from the database and then running user_load on success ...
function my_module_load_user_by_mail($mail){
$query = db_select('user', 'u');
$uid = $query->fields('u', array('uid'))->condition('u.uid', $mail)->execute()->fetchField();
if($uid){
return user_load($uid);
}else{
return FALSE;
}
}
Module function is called instead and passed email ...
$user = my_module_load_by_mail($mail);

Just for background, user_load_from_mail()'s code relies on a $conditions parameter passed to user_load_multiple() that has been deprecated in 8.
Here's my stab at code that will probably be what's in user_load_from_mail() in future.
<?php
function load_user_by_email( $email )
{
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'user')
->propertyCondition('mail', $email);
$result = $query->execute();
// not found?
if (!isset($result['user'])) return;
// found, keys are uids
$uids = array_keys($result['user']);
$account = user_load($uids[0]);
return $account;
}
Nb. There's theoretically no need to check for 2+ values returned since drupal insists emails are unique.

Related

How to use findAll() in yii2?

I want to know how can i get all data of user with array id for where condition
In yii you could do something like this
$students = Student::model()->findAll("id IN ({$_POST['studentIds']})");
or
$userDtls = Student::model ()->findAllByAttributes ( array (
'id' => explode ( ",", $_POST ['studentIds'] )
) );
Now in yii2 CDbCriteria is not there, so which approach should i use to achieve same thing??
I have tried this but it only returns data for first id in the array
$result = Users::findAll([ 'id'=> $_POST ['keylist']]);
In documentation it is written that we can use this
$result = Users::findAll([1,488,489]);
But my array $_POST['keylist'] is something like this
keylist{
0='1'
1='5'
2='8'
}
I have also tried this
$ids = \Yii::$app->request->post('keylist', []);
$result = Users::findAll($ids);
And still returns data for first id in the array here is the screenshot
Thats why it doesnt work i guess
thank you
$users = Users::findAll($ids); is a correct approach.
See what you can pass in $ids in official docs here.
As I explained you here, you should never trust data from $_POST and check it for existence and validate before using.
Example of getting and check for existence with Yii2:
$ids = \Yii::$app->request->post('ids');
Or just:
$ids = isset($_POST['ids']) ? $_POST['ids'] : null;
For more complex cases I'd recommend to create separate search model and use it with validation, see Gii's CRUD for example.
UPDATE: Pay attention to what you actually pass as $ids.
$students_ids = Yii::$app->request->post('studentIds');
if(isset($students_ids)) {
$result = Users::find()->where(['in','id',$students_ids])->all();
}
var_dump($result)
Try like this

Drupal 7, block on all profile pages. Printing fields from 'viewed user' not 'current user'

I'm trying to print a few fields in a block on each profile page.
The block needs to display the fields of the user being viewed, not the logged in user.
$account = user_load($node->uid); - doesn't work. user->uid doesn't either.
Globals user will return the logged in users info.
Not exactly sure how I'm supposed to load anything into a block. Any idea?
Assuming you're viewing a user profile with a URL path like this
drupal/user/USER_ID
You can do as follows :
// Option 1
$user = explode('/', current_path());
$user_id = end($user);
// Option 2
// $path = explode('/', current_path());
// $user_id = $path[count($path)-1];
$account = user_load($user_id, true);
Documentation current_path()
This way you get the last part of the URL and pass it to the user_load function. We set true as second parameter so it loads from the DB and not the cache.
Another way to do the same without breaking the URL into pieces is to use arg() to get the parameters
In this case the code would look like this
// Option 3
// drupal/user/USER_ID
// drupal = arg(0)
// user = arg(1)
// USER_ID = arg(2)
$account = user_load(arg(2), true);
In both cases check that $user_id is an integer, do not let it pass at least is an integer, then you can check the result of user_load.
Update
If you are using the user's name in the URL you can load a full user object by using user_load_by_name()
So the code would change a little bit. Try this :
$account = user_load_by_name(arg(2));
I used arg for simplicity, you can get the user's name from URL as you want.
Hope it helps.

Trying to write a simple Joomla plugin

Please help, this is my first plugin I'm writing and I'm completely lost. I'm trying to write and update information in a table in a joomla database using my custom giveBadge() function. The functions receives two different variables, the first variable is the $userID and the second one is the digit 300 which I pass at the bottom of the class using giveBadge(300). At the same comparing the $userID in the Joomla database to ensure that the number 300 is given to the current user logged in the Joomla site.
Thanks in advance.
<?php
defined('JPATH_BASE') or die;
class plgUserBadge extends JPlugin
{
public function onUserLogin () {
$user =& JFactory::getUser();
$userID =& user->userID;
return $userID;
}
public function giveBadge ($userID, &$badgeID) {
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Fields to update.
$fields = array(
'profile_value=\'Updating custom message for user 1001.\'',
'ordering=2');
// Conditions for which records should be updated.
$conditions = array(
'user_id='.$userID,
'profile_key=\'custom.message\'');
$query->update($db->quoteName('#__user_badges'))->set($fields)->where($conditions);
$db->setQuery($query);
try {
$result = $db->query();
} catch (Exception $e) {
// Catch the error.
}es = array(1001, $db->quote('custom.message'), $db->quote('Inserting a record using insert()'), 1);
}
}
giveBadge(300); //attaches to $badgeID
?>
Here is not going well with your code:
You can drop the assign by reference in all your code (&) - you really don't need it, in 99% of the cases.
Use an IDE (for example Eclipse with PDT). At the top of your code you have & user->userID; Any IDE will spot your error and also other things in your code.
Study existing plugins to understand how they work. Here is also the documentation on plugins.
The method onUserLogin() will automatically be called by Joomla when the specific event is triggered (when your plugin is activated). Check with a die("My plugin was called") to see if your plugin is really called
inside onUserLogin() you do all your business logic. You are not supposed to return something, just return true. Right now your method does absolutely nothing. But you can call $this->giveBadge() to move the logic to another method.

Receive model data inside a CakePHP model callback function

I try to use existing model data inside a models callback function in CakePHP 2.1 but can't get it working.
What I do is I try to get a users role in the beforeValidate() callback and check if it's empty. If yes, I'll set it. Normally I do it like this, and for the first creation of the record it works pretty well.
if (empty($this->data[$this->alias]['role']))
$this->data[$this->alias]['role'] = 'user';
The problem is, every time an existing record (user) gets updated, the role will be set again.
Question: So, how do I check if the field role is already set in the record data, not the post data (seems like $this->data[$this->alias] only contains POST data)?
There are three solutions to this problem as I can see it.
Set a default value in the database column (easiest, best?)
Add role to your inputs everytime.
Lookup the user and add a role if it's missing
The first two options seem obvious, so I'll just illustrate the last.
public function beforeValidate() {
if (!empty($this->id) {
$this->data[$this->alias][$this->primaryKey] = $this->id;
}
if (!empty($this->data[$this->alias][$this->primaryKey])) {
// user exists, check their data
$id = $this->data[$this->alias][$this->primaryKey];
$user = $this->find('first', array(
'conditions' => array($this->primaryKey => $id)
));
$this->data[$this->alias]['role'] = $user[$this->alias]['role'];
}
if (empty($this->data[$this->alias]['role'])) {
// new user but missing a role
$this->data[$this->alias]['role'] = 'user';
}
return true;
}
This callback will check if an ID was passed, and if so it will look up the user and populate the role field. Then, it checks for an empty role and fills it with the default if necessary. Obviously he more code you have, the more possibilities for bugs, so I suggest the first option for default column values.
try:
if (empty($this->data[$this->alias]['role']) && empty($this->role)) {
$this->data[$this->alias]['role'] = 'user';
}

CakePHP User Lookup based on their ID

I thought this would be a relatively common thing to do, but I can't find examples anywhere, and the Cookbook's section on find() was not clear in the slightest on the subject. Maybe it's just something that's so simple Cake assumes you can just do it on your own.
All I'm looking to do here is retrieve a User's name (not the currently logged-in user…a different one) in Cake based on their ID passed to my by an array in the view.
Here's what I've got in the controller:
public function user_lookup($userID){
$this->User->flatten = false;
$this->User->recursive = 1;
$user = $this->User->find('first', array('conditions' => $userID));
//what now?
}
At this point, I don't even know if I'm on the right track…I assume this will return an array with the User's data, but how do I handle those results? How do I know what the array's gonna look like? Do I just return($cakeArray['first'].' '.$cakeArray['last'])? I dunno…
Help?
You need to use set to take the returned data, and make it accessible as a variable in your views. set is the main way you send data from your controller to your view.
public function user_lookup($userID){
$this->User->flatten = false;
$this->User->recursive = 1;
// added - minor improvement
if(!$this->User->exists($userID)) {
$this->redirect(array('action'=>'some_place'));
// the requested user doesn't exist; redirect or throw a 404 etc.
}
// we use $this->set() to store the data returned.
// It will be accessible in your view in a variable called `user`
// (or what ever you pass as the first parameter)
$this->set('user', $this->User->find('first', array('conditions' => $userID)));
}
// user_lookup.ctp - output the `user`
<?php echo $user['User']['username']; // eg ?>
<?php debug($user); // see what's acutally been returned ?>
more in the manual (this is fundamental cake stuff so might be worth having a good read)

Resources