Thursday 28 October 2021

How to Identify whether Logged User has particular custom permission assigned ?

Earlier days we used to use Custom Permission in Visualforce page and Formula fields etc.

We used to assign custom permission to a permission set. and We used to have one utility method to check whether user has permission set or not.

public static Boolean doPermissoncheck(String sPermissionName, String sUserId){
    Boolean isPermAssigned;
    List<PermissionSetAssignment> lstOfAssignment 
    = [SELECT IdPermissionSet.Name,AssigneeId FROM PermissionSetAssignment
      WHERE PermissionSet.Name =:sPermissionName AND AssigneeId=:sUserId];
    isPermAssigned = lstOfAssignment.isEmpty()?false:true;
    return isPermAssigned;
        
}

What If we want to know custom permission from one Permission Set ?
public static Boolean isThisCustomPermissionAssigned(String customPermissionName, 
PermissionSet myPermissionSet){
     CustomPermission customPermission = 
     [SELECT Id FROM CustomPermission WHERE DeveloperName = :customPermissionName Limit 1];
     List<SetupEntityAccess> isPermissionSetAssigned = 
     [SELECT Id FROM SetupEntityAccess WHERE ParentId = :myPermissionSet.Id 
     AND SetupEntityId = :customPermission.Id];
     return !isPermissionSetAssigned.isEmpty();
 }
The key here is the object SetupEntityAccess which act as middle object to connect to
Permission set and Custom Permission, It also act same way when we add
custom permission to Profile.

To add/remove a custom permission from a permission set:
public static void addRemoveCustomPermission(Boolean addNewPermission, 
String sPermissionSetName,String sCustomPermissionName){

    List<PermissionSetLstPermissionSet = 
    [SELECT Id FROM PermissionSet WHERE Label = :sPermissionSetName];
    List<CustomPermission> lstcustomPermission = 
    [SELECT Id FROM CustomPermission WHERE DeveloperName = :sCustomPermissionName];

    if(addNewPermission){
        SetupEntityAccess enablePermission = new SetupEntityAccess
(ParentId=LstPermissionSet[0].IdSetupEntityId=lstcustomPermission[0].Id);
        insert enablePermission;
    }
    else{
        List<SetupEntityAccess> permissionToRemove = [SELECT Id 
FROM SetupEntityAccess 
WHERE ParentId = :LstPermissionSet[0].Id 
AND SetupEntityId = :lstcustomPermission[0].Id];
        delete permissionToRemove[0];
    }
    
}

Now we don't need all these codes to check If user has custom permission assigned or not.
Just one line of code will suffice.
Boolean hasCustomPermission =
FeatureManagement.checkPermission('customPermissionSetname');

https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_class_System_FeatureManagement.htm

Friday 22 October 2021

Apex programming Tricks

Convert List to Map 

Lets assume we have list of accounts record and we need to create map of Id to Account record.

Traditional  approach is using Iterating over list of Account records and storing in a Map. but the easiest approach is 

List<Account> lstofAccount = [Select id,name from Account limit 10];
system.debug('lstofAccount--'+lstofAccount);
Map<Id,Account> map_account = new Map<Id,Account>(lstofAccount);
system.debug('map_account--'+map_account);
11:00:02:011 USER_DEBUG [4]|DEBUG|
map_account--{00111000029360TAAQ=Account:{Id=00111000029360TAAQ
Name=Area Agency on Aging Region 9RecordTypeId=012360000005HcsAAE}, 
00111000029360UAAQ=Account:{Id=00111000029360UAAQName=AULTMAN HOSPITAL
RecordTypeId=012360000005HcsAAE}}

Remove Duplicate Elements from List or Convert List to Set

Most of the time, we may require only unique values from List, the easiest ways is add those value in a set , set will automatically remove duplicate values. How to add list of values to a set without having to iterate 

List<String> lstSFDCTerms = new List<String>
{'Aura','LWC','Lightning','SDLS','Aura','LWC','VF','APEX','JS'};
system.debug('lstSFDCTerms size--'+lstSFDCTerms.size());
Set<String> setOfSFDCTerms =  new Set<String>(lstSFDCTerms);
// we can also do setOfSFDCTerms.addAll(lstSFDCTerms);
system.debug('setOfSFDCTerms size--'+setOfSFDCTerms.size()+'--setOfSFDCTerms--'
+setOfSFDCTerms);

11:21:54:002 USER_DEBUG [2]|DEBUG|lstSFDCTerms size--9

11:21:54:002 USER_DEBUG [4]|DEBUG|

setOfSFDCTerms size--7--setOfSFDCTerms--{APEXAuraJSLWCLightningSDLSVF

How to Use Switch case on String ?

Sometime we may need to check if set contains one particular value then execute particular action. If we have more condition then switch care is better approach as compared to If-else.

Use case - We need to get role Id based on responsibility selected by users. You may have 500 roles defined in your org. What is the best approach ?

for(String sres :responsibility){
   switch on sres {
      when 'Guardian' {
         sRoleId = map_RoleId_Resp.get('Guardian');
         break;
      }
      when 'Legal Guardian Responsible' {
        sRoleId = map_RoleId_Resp.get('Legal Guardian Responsible');
        break;
      }
      when 'Power of Attorney/Healthcare' {
        sRoleId = map_RoleId_Resp.get('Power of Attorney/Healthcare');
        break;
      }
      when 'Durable Power of Attorney/Healthcare' {
        sRoleId = map_RoleId_Resp.get('Durable Power of Attorney/Healthcare');
        break;
      }
      when 'Power of Attorney/Financial' {
        sRoleId = map_RoleId_Resp.get('Power of Attorney/Financial');
        break;
      }
      when 'Durable Power of Attorney/Financial' {
       sRoleId = map_RoleId_Resp.get('Durable Power of Attorney/Financial');
       break;
      }
      when 'Other Legal Oversight' {
       sRoleId = map_RoleId_Resp.get('Other Legal Oversight');
       break;
      }
            
      when else{
          sRoleId = map_RoleId_Resp.get('Portal User');
                break;
      }
}



Wednesday 20 October 2021

How to get record-Id in LWC screen action ?

 If you have created quick action and referred LWC component, you will get "Undefined" as Record Id in ConnectedCallback method, This is the issue I have come across. 

connectedCallback() {
        console.log('connected===============');
        console.log(this.recordId); // This will print undefined.
}

Solutions - 1: We can wrap LWC component with aura, and pass record Id.
<aura:component implements="force:lightningQuickActionWithoutHeader,
force:hasRecordId,force:appHostable>
   <c:updateFiles recordId="{!v.recordId}"/>
</aura:component>

Solution - 2 Use RecordId in component html code.
<div style="display:none">
    {recordId}
 </div>

Component Controller
import { LightningElement,api,track } from 'lwc';
import { CloseActionScreenEvent } from 'lightning/actions';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class UpdateFiles extends LightningElement {
    @api recordId;
   
    connectedCallback() {
        console.log('connected===============');
        console.log(this.recordId);
        
    }
}

Component Code
<template>
    <lightning-quick-action-panel header="Mark Files To Be Deleted">
        <div style="display:none">
            {recordId}
        </div>
        <div slot="footer" class="slds-modal__footer">
     <lightning-button variant="destructive" label="Cancel"></lightning-button>
  <lightning-button class="slds-m-left_x-small" variant="brand" 
label="Delete Files"  onclick={getSelectedRec>
</lightning-button>
            
          </div>
    </lightning-quick-action-panel>
</template>

XML code
<?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>
</targets>
<targetConfigs>
  <targetConfig targets="lightning__RecordAction">
    <actionType>ScreenAction</actionType>
  </targetConfig>
</targetConfigs>
</LightningComponentBundle>