For Everyone

Creating a Custom Component to Update Experience Cloud Profile Photos

5 min read
CloudAnswers photo
CloudAnswers
Share
TODO

Are you looking for a lightning component to set or update a community user’s profile photo? If yes, please read this article for a guide that makes it simple.

A profile photo adds a personal touch to the profile and helps others easily identify the person behind the profile. In the context of professional profiles, a profile photo can convey competence and seriousness. Also, people tend to trust profiles with photos more than those without it. So, most often than not, you will come across a requirement to allow the user to be able to update their profile photo like we did while building a custom profile page for one of our customers.

For building this component, we would need three methods:

  1. Set Community User Profile Photo
  2. Get Community User Profile Photo
  3. Delete Community User Profile Photo

Set Community User Profile Photo

The UserProfiles class under the ConnectApi namespace provides various methods to set, get and delete a user’s profile photo. Let’s look at one such method, setPhoto.


public static ConnectApi.Photo setPhoto(String communityId, String userId, ConnectApi.BinaryInput fileUpload)


This method accepts three parameters:

  1. communityId: This is the Id of the community to which the user is logged in. We can obtain this Id using the Network.getNetworkId method.
  2. userId: This is the Id of logged in user. We can obtain this using the UserInfo.getUserId() method.
  3. fileUpload: This should be an object of ​​ConnectApi.BinaryInput class containing the Blob data, content type and name for image.

Get Community User Profile Photo

Let us say you are building a custom profile page for Experience or Community Cloud users in Salesforce and you want to display a user’s profile photo. Here is how you can get the info about a user’s profile photo which can be used to render their profile photo.

The getPhoto method from UserProfiles class under ConnectApi namespace can be used to get the user profile photo.


public static ConnectApi.Photo getPhoto(String communityId, String userId)


This method accepts two parameters:

  1. communityId: This is the Id of the community to which the user is logged in. We can obtain this Id using the Network.getNetworkId method.

  2. userId: This is the Id of logged in user. We can obtain this using the UserInfo.getUserId() method.

Delete Community User Profile Photo

You have seen how you can set and get a community user photo. There can be multiple reasons when a user would need to delete their profile photo. For e.g: due to change in Organization’s compliance and security policies users may be required to remove their profile photos. So now, you may be wondering how you can allow your users to be able to delete their profile photo from the custom page you built. You’re in luck, we have that answer as well!

We can use the deletePhoto method from the UserProfiles class under ConnectApi for deleting the profile photo.


public static Void deletePhoto(String communityId, String userId)


This method accepts two parameters:

  1. communityId: This is the Id of the community to which the user is logged in. We can obtain this Id using the Network.getNetworkId method.

  2. userId: This is the Id of logged in user. We can obtain this using the UserInfo.getUserId() method.

Putting It Together in Apex class

The output of getCommunityUserPhoto of the above method would look something like this: You can use smallPhotoUrl, mediumPhotoUrl or largePhotoUrl in the src attribute of image tag to render the user profile photo.


public class ProfilePhotoCtrl {

    @AuraEnabled
    public static Map<String, Object> getCommunityUserPhoto() {
        Map<String, Object> result = new Map<String, Object>();
        try {
            // get logged in user id
            String userId = UserInfo.getUserId();
            // get community id
            String networkId = Network.getNetworkId();
            if (networkId != null) {
                // call getPhoto method to retrieve user photo
                ConnectApi.Photo profilePhoto = ConnectApi.UserProfiles.getPhoto(networkId, userId);
                result.put('photo', profilePhoto);
                result.put('status', true);
            } else {
                result.put('status', false);
                result.put('error', 'Invalid Network Id');
            }
        } catch (Exception ex) {
            result.put('status', false);
            result.put('error', ex.getMessage());
        }
        return result;
    }

    @AuraEnabled @RemoteAction
    public static Map<String, Object> setCommunityUserPhoto(String base64Photo, String contentType) {
        Map<String, Object> result = new Map<String, Object>();
        try {
            // get logged in user id
            String userId = UserInfo.getUserId();
            // get the community id
            String networkId = Network.getNetworkId();
            if (networkId != null) {
                String photoName = '';
                if (contentType == 'image/png') {
                    photoName = 'userImage.png';
                } else if (contentType == 'image/jpeg') {
                    photoName = 'userImage.jpg';
                } else {
                    // TODO throw exception
                }
                // convert base64 encoded string to blob
                Blob photoBlob = EncodingUtil.base64Decode(base64Photo);
                // instantiate ConnectApi.BinaryInput object with image data
                ConnectApi.BinaryInput binaryPhoto = new ConnectApi.BinaryInput(photoBlob, contentType, photoName);
                // set the user profile photo
                ConnectApi.Photo profilePhoto = ConnectApi.UserProfiles.setPhoto(networkId, userId, binaryPhoto);
                result.put('status', true);
            } else {
                result.put('status', false);
                result.put('error', 'Invalid Network Id');
            }
        } catch (Exception ex) {
            result.put('status', false);
            result.put('error', ex.getMessage());
        }
        return result;
    }

    @AuraEnabled
    public static Map<String, Object> deleteCommunityUserPhoto() {
        Map<String, Object> result = new Map<String, Object>();
        try {
            // get logged in user id
            String userId = UserInfo.getUserId();
            // get community id
            String networkId = Network.getNetworkId();
            if (networkId != null) {
                // call deletePhoto method from UserProfiles class
                ConnectApi.UserProfiles.deletePhoto(networkId, userId);
                result.put('status', true);
            } else {
                result.put('status', false);
                result.put('error', 'Invalid Network Id');
            }
        } catch (Exception ex) {
            result.put('status', false);
            result.put('error', ex.getMessage());
        }
        return result;
    }

}

The output of getCommunityUserPhoto of the above method would look something like this:


{
 "photo": {
  "fullEmailPhotoUrl": "some_url",
  "largePhotoUrl": "some_url",
  "mediumPhotoUrl": "some_url",
  "photoVersionId": "photo_version_id",
  "smallPhotoUrl": "some_url",
  "standardEmailPhotoUrl": "some_url",
  "url": "some_url"
 },
 "status": true
}

You can use smallPhotoUrl, mediumPhotoUrl or largePhotoUrl in the src attribute of image tag to render the user profile photo.

Custom Lightning Component and Apex Controller

You can find the full source code for Lightning component and Apex class in this GitHub Gist.

If you found this helpful, please don’t hold back your upvotes and you can follow me on Medium or Twitter for more tips and tricks related to Apex, Visualforce, Aura, Lightning Web Components and Salesforce platform.

If you need any help with Salesforce or have something little more complex that might require some advanced developer knowledge, you can contact us at help@cloudanswers.com or chat with us on https://cloudanswers.com


CloudAnswers photo
CloudAnswers
Share

About CloudAnswers

Salesforce apps, powerful components, custom development, and consulting. Our experienced team helps you to create and modify workflow processes in salesforce.

Related Articles

For Everyone

Product Launch: CloudAnswers Shop Builder

Are you looking for an easy way to launch an ecommerce shop? Our new app, Shop Builder, is now in public beta! We’re looking for companies that want to build an online shop but don’t want to spend thousands building it out.

April 12, 2024

5 Min Read

For Everyone

A Day in the Life of a Project Manager at CloudAnswers

I'm Emily, and I've been a project manager at CloudAnswers for the last two years. It can be a nebulous role, but I like to say I act as a bridge between the product vision and tangible results, whether that is building a custom app for a client or one of our own Salesforce products. My typical day revolves around managing tasks, ensuring progress, and maintaining standards while adhering to project timelines.

March 22, 2024

5 Min Read

For Everyone

Create a Custom Lightning Component for Alert and Confirm Dialogs

As front-end developers, there can be numerous instances when we need to display a prompt, a confirm dialog, or a confirm dialog with some input control to accept some value from the user. If you happen to be a Salesforce developer reading this article, you must have had such a requirement while writing lightning components.

March 4, 2024

6 Min Read