Tip of the week # 214 : Lightning Datatable with Mask and Unmasked



Lightning Datatable with Mask and Unmasked

Description : lightning-datatable displays tabular data where each cell with field values and value should be masked and unmasked.
ADVANCED OPTIONS FOR lightning-datatable IN LWC :
  • Component HTML

    
        
        <template>
            <lightning-card title="Related Contacts" icon-name="standard:contact">
                     <lightning-datatable
                        key-field="Id"
                        data={accounts}
                        columns={columns}
                        selected-rows={selectedRowIds}
                        max-row-selection="1"
                        onrowselection={handleRowSelection}
                         onrowaction={handleRowAction}>
                    </lightning-datatable>   
            </lightning-card>
        </template>
        
    	
    	
  • Component JS

    
        
    		import { LightningElement, track, api } from 'lwc';
            import getContacts from '@salesforce/apex/ContactController.getContacts';
            export default class MaskComp extends LightningElement {
                @track accounts;
                @api recordId; 
                columns = [
                    { label: 'First Name', fieldName: 'FirstName', type: 'text' },
                    { label: 'Last Name', fieldName: 'LastName', type: 'text' },
                    { label: 'Email', fieldName: 'maskedEmail', type: 'button', 
                      typeAttributes: { label: { fieldName: 'maskedEmail' },name: 'emailClick', variant: 'base' } },
                    { label: 'Phone', fieldName: 'maskedPhone', type: 'button', 
                      typeAttributes: { label: { fieldName: 'maskedPhone' }, name: 'phoneClick', variant: 'base' } }
                ];
                connectedCallback() {
                    this.loadContacts();
                }
             loadContacts() {
                    getContacts({ accountId: this.recordId })
                        .then(result => {
                            if (result && result.length > 0) {
                                this.accounts = result.map(row => {
                                    return {
                                        ...row,
                                        originalEmail: row.Email,
                                        originalPhone: row.Phone,
                                        maskedEmail: row.Email
                                            ? row.Email.replace(/(.{2})(.*)(?=@)/,
                                                (_, first2, rest) => first2 + '*'.repeat(rest.length))
                                            : '',
                                        maskedPhone: row.Phone
                                            ? 'xxx-xx-' + String(row.Phone).slice(-4)
                                            : ''
                                    };
                                });
                            } else {
                                this.accounts = undefined;
                            }
                        })
                        .catch(error => {
                            console.error('Error loading contacts: ', error);
                            this.accounts = undefined;
                        });
                }
                renderedCallback(){
                    let d = this.template.querySelector('lightning-datatable div');
                    console.log(d);
                }
                handleover(event){
                    console.log(event);
                }
    
                handleRowSelection(event){
                    console.log(event);
                }
                 handleRowAction(event) {
    
                    console.log(event);
                    const rowId = event.detail.row.Id;
                    const actionName = event.detail.action.name;
                    this.accounts = this.accounts.map(row => {
                        if (row.Id === rowId) {
                            if (actionName === 'emailClick') {
                                row.isEmailMasked = !row.isEmailMasked;
                                console.log(row.isEmailMasked);
                                row.maskedEmail = row.isEmailMasked
                                    ? row.originalEmail
                                        : row.originalEmail.replace(/(.{2})(.*)(?=@)/,
                                            (_, first2, rest) => first2 + '*'.repeat(rest.length));
                            }
                            if (actionName === 'phoneClick') {
                                row.isPhoneMasked = !row.isPhoneMasked;
                                row.maskedPhone = row.isPhoneMasked
                                    ? row.originalPhone
                                    : 'xxx-xx-' + String(row.originalPhone).slice(-4);
                            }
                        }
                        return { ...row };
                    });
                }
    
            }
        
    	
    	
  • XML

    
        
    		<!--xml version="1.0"?-->
            <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
                <masterLabel>maskComp</masterLabel>
                <apiVersion>63.0</apiVersion>
                <isExposed>true</isExposed>
                <targets>
                    <target>lightning__HomePage</target>
                    <target>lightning__RecordPage</target>
                </targets>
            </LightningComponentBundle>
        
    	
    	
  • Apex Class

    
        
    		public with sharing class ContactController {
              @AuraEnabled(cacheable=true)
              public static List<Contact> getContacts(Id accountId) {
                  return [
                      SELECT Id, FirstName, LastName, Email, Phone,AccountId
                      FROM Contact WHERE Email != null AND Phone != null AND AccountId =: accountId limit 10
                  ];
              }
          };
        
    	
    	
  • Before :

  • After :

  • Note : Mask patten you can change based business requirement.

Happy Sharing...

Everyone has their own favorites, so please feel free to share with yours contacts and comments below for any type of help!

Use below Chrome Extension for Productivity and share your feedback. Download Link : https://chromewebstore.google.com/detail/quick-shortcuts/ldodfklenhficdgllchmlcldbpeidifp?utm_source=ext_app_menu

Comments

Popular posts from this blog

User Data Privacy

Salesforce LWC : Compact Layout on Hover

Salesforce : Multi-Factor Authentication