LWC
LWC
Populate the Profile_Names__c field with the profiles that should have access to
the LWC component.
Apex Controller:
Write an Apex method to check if the current user's profile matches any of the
profiles listed in the custom metadata. Here’s an example:
apex
Copy code
public with sharing class LWCVisibilityController {
@AuraEnabled(cacheable=true)
public static Boolean shouldDisplayComponent() {
// Get the current user's profile name
String profileName = [SELECT Profile.Name FROM User WHERE Id
= :UserInfo.getUserId()].Profile.Name;
Use the @wire decorator in LWC to call the Apex method and control the visibility
of the component.
javascript
Copy code
import { LightningElement, wire } from 'lwc';
import shouldDisplayComponent from
'@salesforce/apex/LWCVisibilityController.shouldDisplayComponent';
@wire(shouldDisplayComponent)
wiredShouldDisplayComponent({ error, data }) {
if (data) {
this.displayComponent = data;
} else if (error) {
console.error(error);
}
}
}
Template:
Set the Has_Access__c field to true for profiles that should have access to the
component.
Apex Controller:
Write an Apex method to check the custom setting for the current user's profile:
apex
Copy code
public with sharing class LWCVisibilityController {
@AuraEnabled(cacheable=true)
public static Boolean shouldDisplayComponent() {
Profile_Access_Settings__c accessSettings =
Profile_Access_Settings__c.getInstance(UserInfo.getProfileId());
return accessSettings != null && accessSettings.Has_Access__c;
}
}
LWC Component and Template:
The approach here is the same as in the custom metadata method: call the Apex
method using @wire and conditionally render the component based on the response.
Conclusion:
Both approaches are effective for controlling LWC component visibility based on
profiles. The choice between Custom Metadata and Custom Settings may depend on
whether you need hierarchical access (Custom Settings) or a more flexible, reusable
configuration (Custom Metadata).