How to dynamically generate token value based on the input entered in Splunk?

Sample Code:
    <input type="text" token="Degree">
      <label>Instance</label>
      <default>ENTER_THE_DEGREE</default>
      <change>
        <condition match="like(lower($value$),&quot;cs%&quot;)">
          <set token="DegreeFullForm">Computer Science - upper($value$)</set>
        </condition>
        <condition match="like(lower($value$),&quot;it%&quot;)">
          <set token="DegreeFullFormegree">Information Technology - upper($value$)</set>
        </condition>
      </change>
    </input>

    
For input token Degree, if the value is entered as cs or CS, then DegreeFullForm token value will be set as Computer Science - CS.
For input token Degree, if the value is entered as it or IT, then DegreeFullForm token value will be set as Information Technology - IT.

How to allow only pdf files in apex:inputFile in Salesforce?

Sample Code:

Visualforce Page:
<apex:page standardController="Account" extensions="FileUploadController">
    <apex:form enctype="multipart/form-data">
        <apex:outputPanel rendered="{!refreshPage}">
           <script>
              window.top.location='/{!accountId}';
           </script>
        </apex:outputPanel>
        <apex:inputFile accept=".pdf" value="{!objAttachment.Body}" fileName="{!objAttachment.Name}"></apex:inputFile>
        <apex:commandButton value="Load File" action="{!saveFile}"/>
    </apex:form>
</apex:page>

Apex Class:
public class FileUploadController {
    
    public Id accountId { get; set; }
    public Attachment objAttachment { get; set; }
    public Boolean refreshPage { get; set; }

    public FileUploadController(ApexPages.StandardController controller) {
        
        objAttachment = new Attachment();
        accountId = controller.getId();
        refreshPage = false;

    }
           
    public void saveFile() {
        objAttachment.ParentId = accountId;
        insert objAttachment;        
        refreshPage = true;
        
    }

}
 
Output:
 

Add to Campaign is missing in Salesforce

1. Check whether Marketing User checkbox is enabled for the user.


2. Check whether Add to Campaign is added to the List View.


Invalid_Field:Failed to deserialize field at col 0 exception in Salesforce

"Invalid_Field:Failed to deserialize field at col 0" Exception.

Set Date and Date/Time field values based on the running user locale. Check the following article for reference.
https://help.salesforce.com/s/articleView?id=000318296&type=1
 
Follow these steps to resolve this issue:
1. Find the user account which is used to insert or update data.
 
2. Find the Locale of the running user from 1.
 
3.  Check the following article for Date and Date/Time format based on the Locale and update the import file accordingly.
https://help.salesforce.com/s/articleView?id=sf.admin_supported_date_time_format.htm&type=5

IsEscalated(Escalated) field in Salesforce

IsEscalated(Escalated) field in Salesforce
IsEscalated field is used as part of Escalation Rules.

When the Case is escalated by the Escalation Rule, it will display the Escalation icon and set Escalated check box to true. The escalation icon disappears when a case is closed or no longer meets escalation rule criteria.
Reference Article - https://help.salesforce.com/s/articleView?id=sf.cases_fields.htm&type=5

If there is no active Escalation rule and when the Case is closed, the Escalated flag will be set to false.

This record is locked. If you need to edit it, contact your admin Exception in Salesforce

This exception will be thrown when someone tries to edit a record which is locked via Approval Process.

If you are facing this issue while viewing the record, then subscribe to the following known issue

If you have deactivated the approval process, make sure the pending requests are removed.

How to add an entry to list or array in Lightning Web Component in Salesforce?

HTML:
<template>
    <lightning-card title="Array Example" icon-name="custom:custom14">
        <lightning-datatable
            key-field="Id"
            data={listRecords}
            columns={columns}
            hide-checkbox-column="true">
        </lightning-datatable>
        <div class="slds-m-around_medium">
            <lightning-button
                variant="brand"
                label="Add To Array"
                title="Add To Array"
                onclick={handleAddToArray}
                class="slds-m-left_x-small">
            </lightning-button>
        </div>
    </lightning-card>
</template>

JavaScript:
import { LightningElement } from 'lwc';

export default class ArrayExample extends LightningElement {
    
    listRecords;
    i = 0;
    columns = [   
        { label: 'Id', fieldName: 'Id' },
        { label: 'Test 1', fieldName: 'Test1' },
        { label: 'Test 2', fieldName: 'Test2' }
    ];

    handleAddToArray() {

        let newEntry = {
            'Id' : this.i,
            'Test1' : 'Test1 Val ' + this.i,
            'Test2' : 'Test2 Val ' + this.i      
        };

        if ( this.listRecords ) {

            this.listRecords = [ ...this.listRecords, newEntry ];

        } else {

            this.listRecords = [ newEntry ];

        }

        this.i++;

    }

}

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


Output:


lightning:datatable wrap text

Sample Code:
Apex Class:

public class AccountListController {
   
    @AuraEnabled
    public static List < Account > fetchAccts() {
        return [
            SELECT Id, Name, Industry, Type, Description FROM Account LIMIT 10
        ];
    }
   
}

Aura Component:
<aura:component implements="force:appHostable"
                controller="AccountListController">
               
    <aura:attribute type="Account[]" name="acctList"/>
    <aura:attribute name="mycolumns" type="List"/>
   
    <aura:handler name="init" value="{!this}" action="{!c.init}"/>
   
    <lightning:datatable data="{! v.acctList }"
                         columns="{! v.mycolumns }"
                         keyField="Id"
                         hideCheckboxColumn="true"
                         onrowaction="{!c.handleRowAction}"
                         wrapTextMaxLines="3"/>
   
</aura:component>

JavaScript Controller:
({
   
    init: function ( cmp, event, helper ) {
       
        var actions = [
            { label: 'Edit', name: 'edit' },
            { label: 'View', name: 'view' } ];

        cmp.set( 'v.mycolumns', [
            { label: 'Name', fieldName: 'Name', type: 'text' },
            { label: 'Industry', fieldName: 'Industry', type: 'text' },
            { label: 'Type State', fieldName: 'Type', type: 'text' },
            { label: 'Description', fieldName: 'Description', type: 'text', wrapText: true },
            { type: 'action', typeAttributes: { rowActions: actions } } ] );

        var action = cmp.get( "c.fetchAccts" );
        action.setParams({
        });
        action.setCallback(this, function( response ) {
            var state = response.getState();
            if ( state === "SUCCESS" ) {
                cmp.set( "v.acctList", response.getReturnValue() );
            }
        });
        $A.enqueueAction( action );
       
    },

    handleRowAction: function ( cmp, event, helper ) {
       
        var action = event.getParam( 'action' );
        var row = event.getParam( 'row' );
        var recId = row.Id;

        switch ( action.name ) {
            case 'edit':
                var editRecordEvent = $A.get("e.force:editRecord");
                editRecordEvent.setParams({
                    "recordId": recId
                });
                editRecordEvent.fire();
                break;
            case 'view':
                var viewRecordEvent = $A.get("e.force:navigateToURL");
                viewRecordEvent.setParams({
                    "url": "/" + recId
                });
                viewRecordEvent.fire();
                break;
        }
    }
   
})


Output:

"You can't assign a skill to a chat routed with Omni-Channel.: Skill ID" Exception in Salesforce

If we edit the Primary Skill field, then we receive the following error.
"You can't assign a skill to a chat routed with Omni-Channel.: Skill ID"

Label of the field: Primary Skill
API Name of the field: SkillId 

Please check the following article. 
Some fields might not be visible or editable. Primary Skill: Primary Skill is not used for chat and can be empty.

How to publish Platform Event using Apex code?

Sample Code:

List < Test__e > listEvents = new List <Test__e >();
listEvents.add( new Test__e( Serial_No__c = '12345' ) );
listEvents.add( new Test__e( Serial_No__c = '67890' ) );

List < Database.SaveResult > results = EventBus.publish( listEvents );

for ( Database.SaveResult sr : results ) {

    if ( sr.isSuccess() ) {
    
        System.debug( 'Event successfully published event.' );
        
    } else {
    
        for(Database.Error err : sr.getErrors()) {
        
            System.debug( 'Error code: ' + err.getStatusCode() );
            System.debug( 'Error message: ' +   err.getMessage() );
                        
        }
        
    }  
         
}

Files Upload using apex inputFile in Salesforce Visualforce Page

Sample code:
Visualforce Page:
<apex:page standardController="Account" extensions="FileUploadController">
    <apex:form enctype="multipart/form-data">
        <apex:variable var="rowNum" value="{!0}"  />
        <apex:outputPanel id="docTable">
        <apex:outputPanel rendered="{!refreshPage}">
           <script>
              window.top.location='/{!accountId}';
           </script>
        </apex:outputPanel>
            <table cellspacing="5" cellpadding="5">   
                <tr style="{!IF( testDocBool = false, 'display:block', 'display:none' )}">
                    <td>Upload Test File</td>
                    <td><apex:inputFile value="{!testDoc}"/></td>
                </tr>
                <apex:variable var="rowNum" value="{!0}"  />
                <apex:repeat value="{!listAttachments}" var="att">
                    <tr style="{!IF( att.Name ='Test.txt', 'display:block', 'display:none' )}">
                        <td>{!att.Name}</td>
                        <td>
                            <apex:actionRegion >
                                <apex:commandLink value="Remove" reRender="docTable" action="{!delRow}">
                                    <apex:param value="{!rowNum}" name="index" />
                                </apex:commandLink>
                            </apex:actionRegion>
                        </td>
                    </tr>
                    <tr style="{!IF( att.Name ='Test1.txt', 'display:block', 'display:none' )}">
                        <td>{!att.Name}</td>
                        <td>
                            <apex:actionRegion >
                                <apex:commandLink value="Remove" reRender="docTable" action="{!delRow}">
                                    <apex:param value="{!rowNum}" name="index" />
                                </apex:commandLink>
                            </apex:actionRegion>
                        </td>
                    </tr>
                    <apex:variable var="rowNum" value="{!rowNum+1}"/>
                </apex:repeat>
                <tr style="{!IF( test1DocBool = false, 'display:block', 'display:none' )}">
                    <td>Upload Test1 File</td>
                    <td><apex:inputFile value="{!test1Doc}"/></td>
                </tr>
                <tr>
                    <apex:actionRegion >
                        <td><apex:commandButton value="Save" action="{!saveFiles}"/></td>
                        <td><apex:commandButton value="Cancel" action="{!cancelChanges}"/></td>
                    </apex:actionRegion>
                </tr>
            </table>
        </apex:outputPanel>
    </apex:form>
</apex:page>                                       


Apex Class:
public class FileUploadController {

    public List < Attachment > listAttachments { get; set; }
    public List < Attachment > listAttachmentsForDel { get; set; }
    public Boolean testDocBool { get; set; }
    public Boolean test1DocBool { get; set; }
    public Blob testDoc { get; set; }
    public Blob test1Doc { get; set; }
    public Id accountId { get; set; }
    private ApexPages.StandardController stdController;
    public Boolean refreshPage { get; set; }

    public FileUploadController(ApexPages.StandardController controller) {

        stdController = controller;    
        refreshPage = false;        
        testDocBool = false;
        test1DocBool = false;
        listAttachments = new List < Attachment >();
        listAttachmentsForDel = new List < Attachment >();
        accountId = controller.getId();
        listAttachments = [ SELECT Id, Name FROM Attachment WHERE ParentId =: accountId ORDER BY Name ];
        
        if ( listAttachments.size() > 0 ) {
        
            for ( Attachment objAttachment : listAttachments ) {
            
                if ( objAttachment.Name == 'Test.txt' ) {
                
                    testDocBool = true;
                    
                } else if ( objAttachment.Name == 'Test1.txt' ) {
                
                    test1DocBool = true;
                    
                }
            
            }
        }

    }
    
    public void delRow() {
    
        Integer rowNum = Integer.valueOf( ApexPages.currentPage().getParameters().get( 'index' ) );
        system.debug( 'Del Row Num is ' + rowNum );
        Attachment currAttachment = listAttachments.get( rowNum );
        listAttachmentsForDel.add( currAttachment );
        
        if ( currAttachment.Name == 'Test.txt' ) {
                
            testDocBool = false;
            
        } else if ( currAttachment.Name == 'Test1.txt' ) {
        
            test1DocBool = false;
            
        }
        
        listAttachments.remove( rowNum );  
        
    }  
    
    public void saveFiles() {
           
        List < Attachment > listAttachmentsForInsert = new List < Attachment >();
        System.debug( 'testDoc is ' + testDoc );
        System.debug( 'test1Doc is ' + test1Doc );
        
        if ( testDoc != null ) {
                
            Attachment a = new Attachment();
            a.ParentId = accountId;
            a.Name = 'Test.txt';
            a.ContentType = 'text/plain';
            a.Body = testDoc;
            listAttachmentsForInsert.add( a );
            
        }
        
        if ( test1Doc != null ) {
                
            Attachment a = new Attachment();
            a.ParentId = accountId;
            a.Name = 'Test1.txt';
            a.ContentType = 'text/plain';
            a.Body = test1Doc;
            listAttachmentsForInsert.add( a );
            
        }
    
        if ( listAttachmentsForInsert.size() > 0 ) {
            
            insert listAttachmentsForInsert;
            
        }
    
        if ( listAttachmentsForDel.size() > 0 ) {
            
            delete listAttachmentsForDel;
            
        }
        
        cancelChanges();
    
    }
    
    public void cancelChanges() {
    
        refreshPage = true;
        
    }

}


Output:



How to find all required fields within an object in Salesforce?

Option 1: Schema Builder
 

Option 2: Apex
 
Sample code:
Apex Class:
public class Utility {
    
    public static void checkRequiredField( String strObjName ) {
        
        SObjectType objType = Schema.getGlobalDescribe().get( strObjName );
        Map < String, Schema.SObjectField > mapFields = objType.getDescribe().fields.getMap();
        
        for( String strField : mapFields.keySet() ) {
            
            SObjectField field = mapFields.get( strField );
            Schema.DescribeFieldResult fieldResult = field.getDescribe();
            
            if ( !fieldResult.isNillable() && !fieldResult.isDefaultedOnCreate() ) {
                system.debug( fieldResult.getLabel() + ' is required.' );
            }
            
        }
        
    }
    
}

Code to Execute:
Utility.checkRequiredField( 'Employee__c' );
 
Output: 
 

Service Cloud User checkbox in Salesforce

The Service Cloud User feature license entitles users to additional Salesforce features, such as the Service Console.
 
Reference Article:

To assign the Service Cloud User feature license to users, "Manage Internal Users" permission is required

Salesforce Validation Rule to avoid special characters and numbers

Formula:
NOT( REGEX( FIELD ,"[a-zA-Z]*" ) )

Sample Validation Rule:
 

INVALID_SESSION_ID This session is not valid for use with the API in Salesforce

For API and integrations, MFA is not required. Check the following Article.
https://help.salesforce.com/s/articleView?id=000352937&type=1

Disable "Multi-Factor Authentication for API Logins" and check.

Note:
Before the Multi-Factor Authentication for API Logins permission takes effect, users must access Salesforce through the UI and complete MFA using Salesforce Authenticator or a third-party authenticator app. After users have completed MFA through the UI, they can use time-based, one-time passwords (TOTPs) from the app for MFA for API logins.
https://help.salesforce.com/s/articleView?id=sf.security_require_2fa_api.htm&type=5

UNABLE_TO_LOCK_ROW, Unable to obtain exclusive access to this record exception in Salesforce

The error message "unable to obtain exclusive access to this record or 1 records:" indicates that a process was attempting to obtain a lock on a record for 10 seconds before eventually quitting the process with an error message indicating that the record is unavailable.
 
For consistent data, when a record is being created or updated, it is locked so that other users cannot update the record.

FOR UPDATE keyword in SOQL helps us to lock the records from being updating from another request. Sample Code - http://www.infallibletechie.com/2015/05/how-to-lock-records-using-apex-in.html

Locking Issue may happen due to Skewing issue - http://www.infallibletechie.com/2019/11/salesforce-data-skew.html

Salesforce Reference Link - https://help.salesforce.com/articleView?id=000338933&type=1&mode=1

1. Go to Background Jobs under setup and check whether any Sharing Rule Calculation or Picklist field list of value change is happening. If yes, wait for the jobs to complete.


2. Other user may also work on the same record at the same time. So, try after few minutes.

3. If you are using Bulk API for Data Loads, use Serial Mode instead of Parallel mode. If you want to use Parallel mode, make sure child records of the same parent are happening on the same batch of records.

How to detect URL Query Parameters Change and reload the page in Salesforce Lightning Web Component(LWC)?

Quick Action Component:
HTML:

<template>    
</template>

JavaScript:
import { LightningElement, api } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';

export default class SampleQuickAction extends NavigationMixin( LightningElement ) {
    
    @api recordId;

    @api invoke() {

        this[NavigationMixin.Navigate]( {
            type: 'standard__navItemPage',
            attributes: {
                apiName: 'Sample_Tab'
            },
            state: {
                c__recId: this.recordId
            }
        } );

    }

}

js-meta.xml:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>52.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordAction</target>
        <target>lightning__RecordPage</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightning__RecordAction">
            <actionType>Action</actionType>
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>

Tab Component:
HTML:

<template>
    <lightning-card>
        <template if:true={isLoaded}>
            <lightning-spinner alternative-text="Loading..." variant="brand"></lightning-spinner>
        </template>
        <template if:true={recordBool}>
            {recId}
        </template>
        <template if:false={recordBool}>
            Record Id is not passed
        </template>
    </lightning-card>
</template>

JavaScript:
import { LightningElement, wire } from 'lwc';
import { CurrentPageReference } from 'lightning/navigation';

export default class SampleTab extends LightningElement {

    recordBool = false;
    recId;
    currentPageReference;
    connectedBool = false;

    constructor() {

        super();
        console.log( 'Inside Constructor' );
        this.connectedBool = true;

    }
    
    @wire( CurrentPageReference )
    setCurrentPageReference( currentPageReference ) {

        this.currentPageReference = currentPageReference;
        let tempRecId = this.currentPageReference.state.c__recId;
        console.log( 'Rec Id is ' + tempRecId );

        if ( tempRecId ) {

            this.recordBool = true;
            this.recId = tempRecId;

        } else {

            this.recordBool = false;
            this.recId = undefined;
            if ( !this.connectedBool )
                location.reload();
            this.connectedBool = false;

        }

    }
    
}

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


Quick Action:

 
 
Tab:


Output:
 
 
 Navigated from Account:
 

Clicking Sample Tab after navigating from Account(This removes the query parameter):
  
 

Auto-fill from your browser in Salesforce Lightning

Currently, this feature is not available. So, vote for the following idea
 
But, when you create or create a record, it shows those values again. This is based on the Browser Settings. To turn on or off this feature, use the following article.
 
For adjusting the lookup search, check the following article

Trigger to update Account when Contact is Created in Salesforce

Custom Field in Account to update when Contact is created:

Sample Trigger:

trigger ContactTrigger on Contact ( after insert ) {
    
    Set < Id > setAccountIds = new Set < Id >();
    
    for ( Contact objContact : trigger.new ) {
        
        if ( String.isNotBlank( objContact.AccountId ) ) {
            
            setAccountIds.add( objContact.AccountId );
            
        }
    }
    
    if ( setAccountIds.size() > 0 ) {
        
        List < Account > listAccounts = new List < Account >();
        Date dtToday = Date.today();
        
        for ( Id accId : setAccountIds ) {
            
            listAccounts.add( new Account( Id = accId, Last_Contact_Created_Date__c = dtToday ) );   
            
        }
        
        update listAccounts;
        
    }

}

Sub-search or Sub-query in Splunk

search command can be used for sub-search or sub query in Splunk. search command should be within [].
 
Syntax:
main query [search subquery]

Sample Query:
index=abc type=test
[search index=abc *Exception* source=G
earliest=-5d | table requestId] earliest=-5d


Note:
***Sub-search will run first

Changing Master-Detail Lookup to relationship

You can convert a master-detail relationship to a lookup relationship as long as no roll-up summary fields exist on the master object.

Converting a master-detail relationship to a lookup for a custom object on the “detail” side, changes the organization-wide default for the object to public read/write.

Spam Filter in Salesforce Email To Case

Option 1:
You can limit the email addresses or domains available for On-Demand Email-to-Case by entering them in this field, separated by commas in "Accept Email From".


Option 2: 
Usually, email forwarding is used to forward emails from an email account to Salesforce Service Email Address to create Case in Salesforce. So, work with your Email Admin to check whether SPAM Filter can be created before forwarding the Emails to Salesforce Service Email Address.


Outlook:

system.security.NoAccessException: Cannot use IdP while SU'd as another user in Salesforce

Salesforce actively block SSO logins when you are logged in(impersonated) as a different user. As an admin or delegated admin, you can login as an user using Login button on the User Detail Page. So, when you login as an user in Salesforce, it won't login into other dependent applications if they are authenticated via SSO. 
 
 
If you want to test as an user, then create test account in the third party applications and also in the Identity Provider and use the SSO and login. Do not try to test other applications by impersonating as an user in Salesforce.

Field is not writeable: CaseMilestone.IsCompleted in Salesforce

IsCompleted field in CaseMilestone is not Writeable/Editable.

So, this cannot be updated.
 
But, to update the IsCompleted field, update the CompletionDate field. Once the CompletionDate field is updated, the IsCompleted flag will be updated.

Sample code:
update new CaseMilestone( Id = 'IdOfCaseMilestone', CompletionDate = System.now() );

Test class for SObject in Salesforce

Sample Apex Class:
public class Sample {
    
    public static void insertRecord( SObject objRecord ) {
        
        try {
            
            insert objRecord;
            
        } Catch( Exception e ) {
            
            system.debug( 'Exception is ' + e.getMessage() );
        }
        
    }
    
}

Test Class:
@isTest
private class SampleTest {
    
    static testMethod void test() {
        
        Sobject objRecord = new Contact( LastName = 'Testing', Email = 'testing@test.com' );
        Test.startTest();
        Sample.insertRecord( objRecord );
        Test.stopTest();
        Contact objContact = [ SELECT LastName FROM Contact LIMIT 1 ];
        system.assertEquals( objContact.LastName, objRecord.get( 'LastName' ) );
        
    }

}

How to complete a Milestone on a case through Automation in Salesforce?

Requirement:
Mark First Response Milestone as completed when the agent changes the status of the Case from New to Working.
 
Note:
IsCompleted field in CaseMilestone is not Writeable/Editable.

So, this cannot be updated.
 
But, to update the IsCompleted field, update the CompletionDate field. Once the CompletionDate field is updated, the IsCompleted flag will be updated. 

Sample Trigger:

trigger CaseTrigger on Case ( after update ) {

    Set < Id > setCaseIds = new Set < Id >();

    for ( Case objCase : trigger.new ) {
    
        if ( objCase.Status == 'Working' && trigger.oldMap.get( objCase.Id ).Status == 'New' ) {
        
            setCaseIds.add( objCase.Id );
        }        
    
    }
    
    if ( setCaseIds.size() > 0 ) {
    
        List < CaseMilestone > listCaseMilestones = new List < CaseMilestone >();
        
        for ( CaseMilestone objCM : [ SELECT Id, CompletionDate FROM CaseMilestone WHERE CaseId IN: setCaseIds AND MilestoneType.Name = 'First Response' ] ) {
            
            objCM.CompletionDate = System.now();
            listCaseMilestones.add( objCM );
            
        }
        
        if ( listCaseMilestones.size() > 0 ) {
        
            update listCaseMilestones;
            
        }
    
    }

}

How to find all Unique fields within an object in Salesforce?

Sample Code:
 
SObjectType objType = Schema.getGlobalDescribe().get( 'Account' );
Map < String, Schema.SObjectField > mapFields = objType.getDescribe().fields.getMap();

for( String strField : mapFields.keySet() ) {
    
    SObjectField field = mapFields.get( strField );
    Schema.DescribeFieldResult fieldResult = field.getDescribe();
    
    if ( fieldResult.isUnique() ) {
        system.debug( fieldResult.getLabel() );
    }
    
}

Simple File Upload Lightning Web Component in Salesforce for Guest User

HTML:
<template>
    <lightning-file-upload
        label="Attach Supporting Document"
        name="fileUploader"
        record-id={recordId}
        onuploadfinished={handleUploadFinished}>
    </lightning-file-upload>
</template>

JavaScript:
import { api, LightningElement } from 'lwc';

export default class FileUpload extends LightningElement {    

    @api
    recordId;

    handleUploadFinished( event ) {
        
        console.log( 'Record Id is ' + this.recordId );
        const uploadedFiles = event.detail.files;
        alert('No. of files uploaded : ' + uploadedFiles.length);

    }

}

js-meta.xml:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>52.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightningCommunity__Page</target>
        <target>lightningCommunity__Default</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightningCommunity__Default">
            <property
                name="recordId" type="String"
                label="Record Id" />
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>


File Settings:
 

Experience Builder Configuration:


Output:
 


How to allow Guest user to view Files attached to the record in Salesforce Experience Cloud?

Sample Code:

Apex Class:

public with sharing class ExistingFilesController {

    @AuraEnabled( cacheable = true )
    public static List < ContentDocument > fetchContentDocuments( String strRecordId ) {

        List < ContentDocument > listContentDocs = new List < ContentDocument >();

        for ( ContentDocumentLink objCDL : [ SELECT Id, ContentDocument.Title, ContentDocumentId, LinkedEntityId FROM ContentDocumentLink WHERE LinkedEntityId =: strRecordId ] ) {

            listContentDocs.add( new ContentDocument( Id = objCDL.ContentDocumentId, Title = objCDL.ContentDocument.Title ) );

        }
        return listContentDocs;
    }

}

LWC:
HTML:

<template>
    <template if:true={recordsPresent}>
        <lightning-card>
            <lightning-datatable
                key-field="Id"  
                data={listContentDocs}  
                columns={columns}  
                hide-checkbox-column="true"  
                show-row-number-column="true"
                onrowaction={handleRowAction}>  
            </lightning-datatable>
        </lightning-card>
    </template>
</template>

JavaScript:
import { api, LightningElement, wire } from 'lwc';
import fetchContentDocuments from '@salesforce/apex/ExistingFilesController.fetchContentDocuments';
import { NavigationMixin } from 'lightning/navigation';
const actions = [
    { label: 'View', name: 'view' }
];

export default class ExistingFiles extends NavigationMixin( LightningElement ) {

    @api
    recordId;
    columns = [  
        { label: 'Id', fieldName: 'Id' },  
        { label: 'Title', fieldName: 'Title' },
        {
            type: 'action',
            typeAttributes: { rowActions: actions },
        }
    ];  
    recordsPresent = false;

    @wire( fetchContentDocuments, { strRecordId: '$recordId' } )
    wiredRecs( { error, data } ) {

        if ( data ) {

            console.log( 'Records are ' + JSON.stringify( data ) );
            this.listContentDocs = data;
            this.recordsPresent = true;

        } else if ( error ) {

            console.log( 'Error ' + JSON.stringify( error ) );

        }
        
    }
    
    handleRowAction( event ) {

        console.log( 'Inside Handle Row Action' );
        const row = event.detail.row;
        this[ NavigationMixin.Navigate ]( {
            type: 'standard__recordPage',
            attributes: {
                recordId: row.Id,
                actionName: 'view'
            }
        } );

    }

}

JS-meta.xml:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>52.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightningCommunity__Page</target>
        <target>lightningCommunity__Default</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightningCommunity__Default">
            <property
                name="recordId" type="String"
                label="Record Id" />
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>


Experience Builder Configuration:


Output:



Showing Image in Lightning Layout Item in Salesforce LWC

Sample Code:

HTML:

<template>
    <lightning-card>
        <div class="c-container">
            <lightning-layout>
                <lightning-layout-item padding="around-small">
                    <div class="header-column">
                        <img
                            src="https://infallibletechie8-dev-ed--c.documentforce.com/servlet/servlet.ImageServer?id=0155f000000F6it&oid=00D5f000001y2Vs"
                            height="200"
                            width="200"/>
                    </div>
                </lightning-layout-item>
            </lightning-layout>
        </div>
    </lightning-card>
</template>

JavaScript:
import { LightningElement } from 'lwc';

export default class LightningLayout extends LightningElement {}

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


Output:


How to create Case from Einstein BOT only when Chat is transferred to an agent and change the owner in Salesforce?

1. Create a Flow to create Case record. The flow will be called from the BOT when the Chat is transferred to the agent.







2.Create the following trigger on AgentWork entity.
 
trigger AgentWorkTrigger on AgentWork ( after update ) {

    Set < Id > setChatIds = new Set < Id >();

    for ( AgentWork objAWT : trigger.new ) {
    
        String strWorkItemId = objAWT.WorkItemId;
    
        if ( objAWT.AcceptDateTime != null && trigger.oldMap.get( objAWT.Id ).AcceptDateTime == null && strWorkItemId.startsWith( '570' ) ) {
        
            setChatIds.add( objAWT.WorkItemId );
        
        }
    
    }
    
    if (setChatIds.size() > 0 ) {
    
        List < Case > listCases = new List < Case >();
    
        for ( LiveChatTranscript objLCT : [ SELECT Id, OwnerId, CaseId FROM LiveChatTranscript WHERE Id IN: setChatIds AND CaseId != null ] ) {
        
            listCases.add( new Case( Id = objLCT.CaseId, OwnerId = objLCT.OwnerId ) );
        
        }
        
        if ( listCases.size() > 0 ) {
        
            update listCases;
            
        }
    
    }

}
 
3. Call the flow from BOT from Transfer to Agent Dialog.
 

Output: