How can I make this function run - also when getUsername() is null
$authSession = $objectManager->get('Magento\Backend\Model\Auth\Session');
$UUsername = $authSession->getUser()->getUsername();
We should not be using Object Manager as this can cause issues. For getting admin username we are going to want to add these classes to our constructor.
protected $authSession;
public function __construct(
....
\Magento\Backend\Model\Auth\Session $authSession,
....
) {
....
$this->authSession = $authSession;
....
}
then we can get our user like this:
$this->authSession->getUser()
this will give you the current logged in admin.
You can later get the details like $user->getUsername()
or $user->getEmail().