function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Chris RonnieChris Ronnie 

Getting the Agent Image and the Agent Name for Live Agent

So I have build a custom chat page that gets the agents photo. When I say built.... I mean borrowed from here https://systemdebug.wordpress.com/2015/05/17/live-agent-rest-api-connectapi/

What I want to do now is also get the agents name. 

The current Apex Class is
 
public without sharing class Chatwindowcontroller {
	
	@RemoteAction
	public static String getPhoto(String userId)
	{
		ConnectApi.Photo p = ConnectApi.ChatterUsers.getPhoto(Network.getNetworkId(), userId);
		return p.smallPhotoUrl;
	}
}

How do I extend this to also get the agents name. When I then have it how do I use it in my Visualforce page?
Best Answer chosen by Chris Ronnie
VineetKumarVineetKumar
In the above code, the variable AgentId was not defined.
On Controller:
    public without sharing class ChatWindowController {
        
        public String userName {get; set;}
        public String AgentId {get; set;}

        public ChatWindowController(){
            AgentId=Apexpages.currentpage().getparameters().get('id');
            ConnectApi.UserDetail userDetail = ConnectApi.ChatterUsers.getUser(Network.getNetworkId(), AgentId);
            userName = userDetail.Name;
        }
        
        @RemoteAction
        public static String getPhoto(String userId)
        {
            ConnectApi.Photo p = ConnectApi.ChatterUsers.getPhoto(Network.getNetworkId(), userId);
            return p.smallPhotoUrl;
        }
    }


On Page:
    <apex:outputText value="{!userName}" />

 

All Answers

VineetKumarVineetKumar
Hi, 
Can you use this
ConnectApi.UserDetail userDetail = ConnectApi.ChatterUsers.getUser(Network.getNetworkId(), userId);
system.debug('#### User Name = '+userDetail.Name);
Chris RonnieChris Ronnie
I will try. How would I then call the output in a div in a visualforce page?

{userDetail.Name}

??
VineetKumarVineetKumar
If it is just the name that you require, then you can define a String variable in your controller and set this value to it. Which you will eventually be using in your page.
public String userName {get; set;}
userName = userDetail.Name;

<apex:outputText value="{!userName}" />

Or if you require other value as well, then you can use something like below.
ConnectApi.UserDetail userDetail {
	get{
		return userDetail;
	}
	set{
		userDetail = ConnectApi.ChatterUsers.getUser(Network.getNetworkId(), userId);
	}
}

<apex:outputText value="{!userDetail.Name}" />
<apex:outputText value="{!userDetail.Email}" />

 
Chris RonnieChris Ronnie
OK so super newbie question. I already have this:
public without sharing class ChatWindowController {
    
    @RemoteAction
    public static String getPhoto(String userId)
    {
        ConnectApi.Photo p = ConnectApi.ChatterUsers.getPhoto(Network.getNetworkId(), userId);
        return p.smallPhotoUrl;
    }
}
How do I then add this:
public String userName {get; set;}
userName = userDetail.Name;

<apex:outputText value="{!userName}" />
to the same class? Sorry as you can possible tell I am not a developer :)
 
VineetKumarVineetKumar
On Controller:
    public without sharing class ChatWindowController {
        
        public String userName {get; set;}

        public ChatWindowController(){
            ConnectApi.UserDetail userDetail = ConnectApi.ChatterUsers.getUser(Network.getNetworkId(), userId);
            userName = userDetail.Name;
        }
        
        @RemoteAction
        public static String getPhoto(String userId)
        {
            ConnectApi.Photo p = ConnectApi.ChatterUsers.getPhoto(Network.getNetworkId(), userId);
            return p.smallPhotoUrl;
        }
    }


On Page:
    <apex:outputText value="{!userName}" />
Chris RonnieChris Ronnie
A billion thanks!!! Going to try and it now.
VineetKumarVineetKumar
Sure, let me know if it helped.
Chris RonnieChris Ronnie
Getting this error

Error: Compile Error: Variable does not exist: userId at line 6 column 104

it doesnt like this line

ConnectApi.UserDetail userDetail = ConnectApi.ChatterUsers.getUser(Network.getNetworkId(), userId);

Sorry for being a pain :(
VineetKumarVineetKumar
No issues.
The userId to be used here is same as you are using for this method :
public static String getPhoto(String userId)

Just to know the background, what is the userId? is it the logged in user?
Chris RonnieChris Ronnie
Yes the userId is the ID of the logged in user. What I need returned is 

return UserInfo.getFirstName() ;
return UserInfo.getLastName() ;

I then need a way to use this data in a Visual Force page.

 
VineetKumarVineetKumar
Ah! perhaps I would have asked you earlier.
It's pretty straightforward then. No need for any thing to be done in controller.
Just use the below tag in your VF page.
<apex:outputText value="{!$User.Alias}" />
Refer below link to get more details
https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_variables_global_user.htm
Chris RonnieChris Ronnie
I am so close now to the solution! What it is returning is not the username, but Guest. 

I should have mentioned this too, this is for Live Agent, so the customisation is running from a public site. It is being triggered from a website. I think I need to allow the sites public profile read access to the user object.
VineetKumarVineetKumar
I just gave you an example. you can use the above to get any data for the logged in User.
<apex:outputText value="{!$User.FirstName}" />
<apex:outputText value="{!$User.LastName}" />
<apex:outputText value="{!$User.Name}" />
<apex:outputText value="{!$User.Email}" />

and so on....

 
Chris RonnieChris Ronnie
Ah so I have just worked out this is not what I need. $User.FirstName is returning the name of the force.com public user (Guest) What I need returned is the name of the live agent user that is chatting to the user.

User-added image
VineetKumarVineetKumar
Ok so this is not actually the logged in user that said above, it is the live chat agent who is chatting.
Then you will have to use the below code.
Where userId is the Id of the Livechat Agent, the same value that you are passing in tht getPhoto method.
On Controller:
    public without sharing class ChatWindowController {
        
        public String userName {get; set;}

        public ChatWindowController(){
            AgentId=Apexpages.currentpage().getparameters().get('id');
            ConnectApi.UserDetail userDetail = ConnectApi.ChatterUsers.getUser(Network.getNetworkId(), AgentId);
            userName = userDetail.Name;
        }
        
        @RemoteAction
        public static String getPhoto(String userId)
        {
            ConnectApi.Photo p = ConnectApi.ChatterUsers.getPhoto(Network.getNetworkId(), userId);
            return p.smallPhotoUrl;
        }
    }


On Page:
    <apex:outputText value="{!userName}" />
Try the above and let me know if it helped. If not please share both your page and controller here, so that I can have a look as to how and what agent Id you are setting.
Chris RonnieChris Ronnie
When I try this controller code I get this error

Error: Compile Error: Variable does not exist: AgentId at line 6 column 13

I tried changing this
AgentId=Apexpages.currentpage
to this
AgentId = Apexpages.currentpage
This is my VF page
 
<apex:page docType="html-5.0" showHeader="false" controller="ChatWindowController" cache="true"> 
<link rel="stylesheet" type="text/css" href="{!$Resource.chatstyle}"/>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"> </script>
<script type='text/javascript'>  

        liveagent.addEventListener(liveagent.chasitor.Events.CHAT_ESTABLISHED, newagent);
        liveagent.addEventListener(liveagent.chasitor.Events.AGENT_CHAT_TRANSFERRED,newagent);
                
        function newagent() {           
            var newagentId;
            var details = liveagent.chasitor.getDetails();          
            for(var key in details) {                       
                if (key == 'agent'){                    
                    newagentId = details[key].userId;
                }
            }
            if (newagentId != null ){               
                Visualforce.remoting.Manager.invokeAction(
                '{!$RemoteAction.ChatWindowController.getPhoto}', 
                newagentId, 
                function(result, event){
                    if (event.status) {                           
                            $("#agentphoto").attr("src",result);
                    } else if (event.type === 'exception') {                        
                            console.log(event.message);
                    } else {
                        console.log(event.message);
                    }
                }
             );         
            }
        }
</script>

    <div style="top: 5px; left: 0; right: 0; bottom: 0; position: absolute;">
        <liveAgent:clientchat >
            <liveAgent:clientChatSaveButton label="Save Chat" />
            <liveAgent:clientChatEndButton label="End Chat" />
            <div id="photo-container" class="photocontainer">
                    <img id="agentphoto" src=""/>
            </div>
              <div id="agentname"><apex:outputText value="{!userName}" />
 
            <br>Customer Service Superstar</br>
            </div>
            <div id="lwrlogo"> <img src="{!$Resource.lwrlogo}" height ="100" width= "100" />
            
            </div>
            <div style="top: 110px; left: 5px; right: 5px; bottom: 5px; position: absolute; z-index: 0;">
                <liveAgent:clientChatAlertMessage />
                <liveAgent:clientChatStatusMessage />
                <table id="waitingMessage" cellpadding="0" cellspacing="0">
                <tr>
                <td>Please wait while you are connected to an available agent.</td>
                </tr>
                </table>
                
                <div style="top: 0; right: 0; bottom: 41px; left: 0; padding: 0; position: absolute; word-wrap: break-word; z-index: 0;">
                <liveAgent:clientChatLog />
                </div>
                <div style="position: absolute; height: auto; right: 0; bottom: 0; left: 0; margin-right: 67px;">
                    <liveagent:clientChatInput /><liveAgent:clientChatSendButton label="Send"/>
                </div>
            </div>
        </liveAgent:clientchat>
    </div>
</apex:page>



 
VineetKumarVineetKumar
In the above code, the variable AgentId was not defined.
On Controller:
    public without sharing class ChatWindowController {
        
        public String userName {get; set;}
        public String AgentId {get; set;}

        public ChatWindowController(){
            AgentId=Apexpages.currentpage().getparameters().get('id');
            ConnectApi.UserDetail userDetail = ConnectApi.ChatterUsers.getUser(Network.getNetworkId(), AgentId);
            userName = userDetail.Name;
        }
        
        @RemoteAction
        public static String getPhoto(String userId)
        {
            ConnectApi.Photo p = ConnectApi.ChatterUsers.getPhoto(Network.getNetworkId(), userId);
            return p.smallPhotoUrl;
        }
    }


On Page:
    <apex:outputText value="{!userName}" />

 
This was selected as the best answer
VineetKumarVineetKumar
Alternative

Also, I can see on line 14
details[key] is already having the agent details.
Using JS you can the name and set it to the html component

Something like,
details[key].Name and assign that value to the html component
Chris RonnieChris Ronnie
OK I am back again :)

I still like the idea of using the controller. I have made the changes in my sandbox and it all looks great. Of course the issue is now I need to move it to production and my test coverage is only 33%

My test class looks like this
 
@isTest(SeeAllData=true)
public class Test_ChatWindowController {
    
    static testMethod void testChatWindowController() {
        System.Debug ('Starting!');
        test.starttest();
            System.Debug (ChatWindowController.getPhoto('00590000001HYfH'));
            System.Debug (ChatWindowController.AgentId ('00590000001HYfH'));
            System.Debug (ChatWindowController.userName ('00590000001HYfH'));
        test.stoptest();
    }
}

The error I get for line 8 is
 
Method does not exist or incorrect signature: ChatWindowController.AgentId(String)


 
VineetKumarVineetKumar
No, this is not the way you write a test class.. :)
As I can see you are hardcoding Id's which is not allowed, as these Id's may not be present on production, resulting in test class failure during deployment.
 
PageReference pageRef = Page.<API_Name_of_the_page>;
Test.setCurrentPage(pageRef);
ApexPages.currentPage().getParameters().put('id', <agent_id>);
ChatWindowController ccObject =  new ChatWindowController ()
ChatWindowController.getPhoto(<agent_id>);
replace with relevant values between <>

you can refer few articles as in below 
https://developer.salesforce.com/page/An_Introduction_to_Apex_Code_Test_Methods

To help the community grow, do mark the answers with likes or best answer, so as to help anyone face similar issue in future.
 
Chris RonnieChris Ronnie
OK so more issues. I feel close to a solution but it is just out of reach!!

Seems the latest bit of code has introduced a permissions issue.

Authorization Required Error Message

I have checked the permissions for the visualforce page and the apex class and they both have the full force.com user permissions.
VineetKumarVineetKumar
Looks like a community or portal to me. Have you added the profiles to the community?
Chris RonnieChris Ronnie
OK I have changed my solution. I had an issue with some force.com stuff so I am trying this.

My Class now looks like this
 
public without sharing class ChatWindowController {
    
    @RemoteAction
    public static String getPhoto(String userId)
    {
        ConnectApi.Photo p = ConnectApi.ChatterUsers.getPhoto(Network.getNetworkId(), userId);
        return p.smallPhotoUrl;
    }
    @RemoteAction
    public static String getUserStuff(String userId)
    {
        User UserStuff = [Select firstname,lastname from user where id =: userId];
        return UserStuff.firstname + UserStuff.lastname;
    }
}

I have updated my visualforce page to have this:
 
if (newagentId != null ){               
                Visualforce.remoting.Manager.invokeAction(
                '{!$RemoteAction.ChatWindowController.getUserStuff}', 
                newagentId, 
                function(result, event){
                    if (event.status) {                           
                            $("#agentname").attr("src",result);
                    } else if (event.type === 'exception') {                        
                            console.log(event.message);
                    } else {
                        console.log(event.message);
                    }
How do I just get the results of getUserStuff to display has plain html here
 
$("#agentname").attr("src",result);


 
Jaya Koti MuleJaya Koti Mule
Hi Chris Ronnie,

Were you able to solve the above issue. Displaying Live agent name on the custom chat page? Please post the code if you were successfull.
When I tried the above code selected as the Answer, the agentId is getting null.
Akshata c 4Akshata c 4
Hi Chris Ronnie,

I have added ChatWindowController code in apex class section i am getting this error
"Error: Compile Error: Method was removed after version 34.0: getPhoto at line 6 column 54". This getPhoto method removed.
Erin KuhnErin Kuhn
Akshata c 4, having the same error message. Did you ever find a solution?