How to get the current user object in Drupal 8? - php

I am proficient in Drupal 7 where I get the current user object from global $user, but how do I get it in Drupal 8 ?

One liner way to get a full drupal user object for the current active user :
$account = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
Why not just Drupal::currentUser() ? Because most of the time it won't be sufficient as you'll need a fully loaded user object while it's not :
\Drupal::currentUser() returns an AccountProxyInterface.
\Drupal\user\Entity\User::load() actually returns a user entity object.

Please use following code to get the current user object in Drupal 8:
$user = \Drupal::currentUser();

According to entity api, we should not use User::load. Instead, use entityTypeManager like so :
$user_id = \Drupal::currentUser()->id();
$user_entity = \Drupal::entityTypeManager()->getStorage('user')->load($user_id);

$user = \Drupal::currentUser();
To get the current userID you can use :
$user = User::load(\Drupal::currentUser()->id());

Related

Class name must be a valid object or a string Laravel 5.7

I want to save a new record, but Laravel gives me this error Class name must be could object or a string. my code;
public function store(Request $request)
{
$question = new Question;
$question->question = $request->question;
$question->question_type_id = $request->question_type;
$question->user_id = $request->Auth::id();
$question->save();
}
Note: My PHP version is latest .i.e., 7.1.9
I assume you created an input field that has a name of the user’s id and you are trying t access it with
$request->Auth::id()
Which for a user with a user id of one, I assume you are asking to pass request item $request->1.
This won’t work as Auth::id() is being passed as a literal. Accessing the request object it’s complaining saying ‘hey, I can’t accept a class as a variable name, please stop!
If this is in fact what you are trying to do, and Auth::id() works (I never used that, I typically use Auth::user()->id), then you would have to pass the function within parentheses like this:
$request->(Auth::id())
right syntax for dynamic object key is :
$question->user_id = $request->{Auth::id()};
or if you just want auth id, then it is
$question->user_id = Auth::id();
I have fixed this issue, thanks to aynber for sorting out my issue. I have changed
$question->user_id = $request->Auth::id();
to
$question->user_id = Auth::id();

Easiest way to retrieve a single field from database with Fat-Free Framework?

What is the easiest way to retrieve the value of a single field from a MySQL database using Fat-Free Framework? I have been able to do it with the following code which returns an array but am wondering how to improve this:
$result = $db->exec('SELECT id FROM admins WHERE username = ?',$f3->get('POST.username'));
This query returns the id field that we are seeking in an array which is accessible via $result[0]['id'] - can we avoid assigning this to an array and read it directly to a string variable?
Depending on which version of PHP you're using you could possibly do this..
$result = $db->exec('SELECT id FROM admins WHERE username = ?',$f3->get('POST.username'))[0]['id'];
or if you were using pure PDO you could use fetchColumn(), but you're using a framework. The only way to change the returned value is to edit the framework code.
I realise this is an old question but I ran into the same problem recently and came up with the findone() function. I wanted to share it as it had not been mentioned before in case anyone else is looking for a solution.
$f3=\Base::instance();
$f3->set('DB',new DB\SQL('sqlite:db/database.sqlite'));
$admins = new \DB\SQL\Mapper($f3->get('DB'), 'admins');
$username = $admins->findone(['username = ?', $f3->get('POST.username')])->username;
Line 1-3 are just preliminaries. You'll need a table mapper to use this function. Line 4 is a one-liner which will set the $username to hold the actual value of the username.
You should use Cursor/Mapper.
Something Like:
\Base::instance()->set('DB',new DB\SQL('sqlite:db/database.sqlite'));
$admins_mapper = new \DB\SQL\Mapper(\Base::instance()->get('DB'), 'admins');
$admin = $admin_mapper->load(array('username = ?', \Base::instance()->get('POST.username'));
You can also use Cortex which is build on top of Cursor.

ZF2: getting user session_id

I need to get session_id() in ZF2? Using session_id() won't return any value. I tried Zend_Session::getId() but it didn't work, probably because I haven't included the path (which I don't know).
Can anyone help me to find a solution. Thanks in advance.
session_id() should work, but the correct way would be to access it from the session manager, e.g. (from a controller):
$sessionManager = $this->getServiceLocator()->get('Zend\Session\SessionManager');
$id = $sessionManager->getId();
If neither of these are returning a value for you then there's another problem somewhere.
first of all you have to use zend session container in your page that is.
use Zend\Session\Container;
now create an object of container by following.
$session = new Container('User');
now set value $userid or any other variable in session by following object.
$session->offsetSet('userId', $id);
now you can get it by following code.
$user_id=$session->offsetGet('userId');

Joomla: difference between JFactory::getUser and JUserHelper::getProfile

$profile = JFactory::getUser($this->_user_id);
$userDetails = JUserHelper::getProfile($this->_user_id);
$profile->details = isset($userDetails->profile) ? $userDetails->profile : array();
I'd like to know the difference between the two function JFactory::getUser() and JUserHelper::getProfile().
And what do those 3 lines of code do?
An informative answer will be highly appreciated.
Thank you!
While JFactory::getUser() method, returns the global JUser object (from where you can access the JUser methods, the JUserHelper::getProfile() returns the integer for user id. From here, it's your decision to choose what you need in your specific case - if just the use id integer or the JUser object.
$profile->details will not be set as it is not a property of the JUser object. This most certainly will throw you a PHP notice.

How to change a Joomla User Group with php

In a Joomla 2.5 site I want to assign a registered user to another group after they complete a form. The user would be logged in when they complete the form which will be created in Fabrik so that I can add a PHP script to run on save. My php skills are rudimentary. What would the lines in php look like that adds the current user to a group?
You can use JUserHelper::setUserGroups to set the group(s) of a user.
To retrieve the current user you can use JFactory::getUser.
When you have the user, you can (I haven't confirmed this) probably get the id right away. Some non-tested code which will hopefully get you on the way:
$user = JFactory::getUser();
$userId = $user->id;
JUserHelper::setUserGroups($userId, 3);
Or in short:
JUserHelper::setUserGroups(JFactory::getUser()->id, 3); // 3 Is the group number
You can find the group ID's by going into the table-prefix_usergroups table and retrieve the primary key. I haven't found a way to retrieve a list of groups without going into the database, but this may help.
A screenshot of my (non-edited) database with usergroups:
Here I used a different approach as JUserHelper::setUserGroups method always failed with my Joomla 3.3.1 installation.
$user = JFactory::getUser();//get current user
$g = array('2'=>2,'3'=>3);//2 for registered user, 3 for author
$user->groups = $g;
$user->save();
I'm using Joomla 3.7.5, and this method worked for me:
JUserHelper::setUserGroups($joomlaId, array(10));
Where, $joomlaId is the id of the user I want to change. This sets the user to only be a member of group 10, and saves the changes to the user DB immediately.
You may also want to look at the addUserToGroup method (since Joomla Platform 11.1)
JUserHelper::addUserToGroup (JFactory::getUser()->id, 3); // 3 Is the group number
So for example if your user was previously in the 'registered' group (id=2), he/she will also be assigned to group 3 after this.
Similarly there is also the removeUserFromGroup method which does the opposite.
As per the documentation, it may be useful to note that the setUserGroups method supports an array for the groups, whereas the other 2 methods I mention here support an integer.
setUserGroups(integer $userId, array $groups) : boolean
addUserToGroup(integer $userId, integer $groupId) : boolean
removeUserFromGroup(integer $userId, integer $groupId) : boolean
https://api.joomla.org/cms-3/classes/JUserHelper.html
I couldn't find any useful way to do this in joomla 3, so here's a quickie for people who just need this to work:
$db = JFactory::getDbo();
$db->setQuery("replace into xo6uf_user_usergroup_map values ($user_id, $group_id)");
$db->query();

Categories