logo

get users programmatically in drupal 8

26 Aug 2022

Method to Get Username Programmatically Drupal 8

Published On: Fri, 08/26/2022 - 19:46

There are several ways to get the user's name programmatically.

$uid = 1;	// For example I have get detail of user ID 1
$account = \Drupal\user\Entity\User::load($uid); // pass your uid

Method 1

drupal_set_message($account->name->value);  

Method 2

drupal_set_message($account->get("name")->value); 

Method 3

drupal_set_message($account->getUsername());

Method 4

drupal_set_messageā€¦
				  

22 Apr 2020

Get user list by role programmatically in Drupal8

Published On: Wed, 04/22/2020 - 22:13

User this code before

use Drupal\user\Entity\User;

Thise code will be return user list of a given role (editor)

	$ids = \Drupal::entityQuery('user')
	->condition('status', 1)
	->condition('roles', 'editor')
	->execute();
	$users = User::loadMultiple($ids);
	foreach($users as $user){
		$username = $user->get('name')->value;
		$uid = $user->get('uid')->value;
		$userlist[$uid] = $username;
	}