Display image in circle using Salesforce Lightning Web Component

Display image in circle using Salesforce Lightning Web Component

lightning-avatar with variant as circle can be used to display image inside a circle using Salesforce Lightning Web Component.

In this Blog Post, I have used Content Asset for storing and managing the images.

Sample Lightning Web Component:

HTML:

<template>           
    <lightning-card title="Contact Information">  
        <lightning-layout>
            <lightning-layout-item padding="around-small">                
                <lightning-avatar 
                    size="large" 
                    variant="circle"
                    fallback-icon-name="standard:contact"
                    alternative-text={contactName}
                    src={assetURL}>
                </lightning-avatar>
            </lightning-layout-item>
            <lightning-layout-item padding="around-small">
                <b>Full Name: </b>{contactName}
                <br/><br/>
                <b>Account Name: </b>{accountName}
            </lightning-layout-item>
        </lightning-layout>
    </lightning-card>
</template>

JavaScript:

import { LightningElement, wire, api } from 'lwc';
import { getRecord } from "lightning/uiRecordApi";
import ACCOUNT_NAME from "@salesforce/schema/Case.Account.Name";
import CONTACT_NAME from "@salesforce/schema/Case.Contact.Name";

export default class ContactHighlight extends LightningElement {

    @api recordId;
    assetURL;
    contactName;
    accountName;

    @wire( getRecord, {
        recordId: "$recordId",
        fields: [ CONTACT_NAME, ACCOUNT_NAME ]
    } )
    wiredRecord({ error, data }) {

        if ( error ) {

            console.log(
                'Error is',
                JSON.stringify(
                    error
                )
            );

        } else if ( data ) {
            
            console.log(
                'Data from wire is', 
                JSON.stringify(
                    data
                )
            );         
            this.objCase = data;   
            this.accountName = data.fields.Account.value.fields.Name.value;
            console.log(
                'Account Name is',
                this.accountName
            );
            this.contactName = data.fields.Contact.value.fields.Name.value;
            console.log(
                'Contact Name is',
                this.contactName
            );
            this.assetURL = '/file-asset/' +
				this.contactName.replace( /\s/g, '' );

        }

    }

}

js-meta.xml:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>59.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

Output:

Sample Image Avatar:

https://www.lightningdesignsystem.com/assets/images/avatar1.jpg

Leave a Reply