[SalesForce] Get current logged in users data in VF page and extension

I want to display the currently logged in users in my VF page.
Calling the following is not allowed:

<apex:outputField label="Raised by" value="{!$User.Id}"/>

I would like to know how else I could display the current user as well as use the details further in my VF controller extension which sends Opportunity data via email:

public class MailExtension
{
  private Opportunity opp;

  public MailExtension(ApexPages.StandardController cont)
  {
    opp =(Opportunity) cont.getRecord();
  }

  public PageReference sendRequest()
  {

    // Email Stuff from Opportunity Data
    Messaging.reserveSingleEmailCapacity(1);
    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
    String[] toAddresses = new String[] {'johndoe@mail.com'};
    mail.setToAddresses(toAddresses);
    mail.setReplyTo('no-reply@salesforce.com');
    mail.setSenderDisplayName('John Doe');
    mail.setSubject('Opportunity Request : ' + opp.Id);
    mail.setBccSender(false);
    mail.setUseSignature(false);
    mail.setPlainTextBody('Your Opportunity: ' + opp.Id +' request.\nCurrent logged in user:' + User.Surname );
    Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });

    return new PageReference('javascript:window.close()'); 
  }
}

Best Answer

You can use userinfo class in apex to obtain the information related to logged in user.

https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_userinfo.htm

You can get Id using userinfo.getUserId() and if userinfo class is not able to provide info use query to query those fields .

On VF you will need to use

 <apex:outputText value="{!$User.Id}">

You are using outputfield and hence you are not able to save the code

Edit::

A sample getter setter User object type variable will be handy

public class MailExtension{
  public user currentuser{get;set;}
  public MailExtension(ApexPages.StandardController cont){
     opp =(Opportunity) cont.getRecord();
     currentuser=new User();
     currentuser=[Select Id,Name,Email from User where Id=:userinfo.getuserId()];
  } 
}

A sample VF tag or mark up will be as follows

<apex:outputfield value="{!currentuser.Id}"/>
<apex:outputfield value="{!currentuser.Email}"/>
Related Topic