Do LWC respect the CRUD access in apex method?

Best practise needs to be addressed while writing a lightning web component. Let’s say you are creating a record through apex method being called in Lightning Web component. Will your LWC respect the CRUD access of the user who is going to create a record?

The answer is no. LWC does not respect the CRUD access. You need to explicitly handle the CRUD access check before inserting the record in Salesforce via a lightning web component.

Example

Lightning Web Component does not respect the CRUD access by default if you are not using Lightning Data Service. Let’s create a component to test it. We have component called createAccounts which below files in its bundle:-

  • createAccounts.html
  • createAccounts.js
  • createAccounts.js-meta.xml

createAccounts.html

The html file consist of a input field and button along with some text message to show the CRUD access. The property named createdAccountId will show the id of the account if created successfully and property called error will show the error message by checking the CRUD access.

<template>
    <lightning-card title="Create Account">
        <lightning-input label="Account Name" onchange={handleOnChange}>
        </lightning-input>
        <lightning-button variant="brand" label="create account" title="create account" onclick={handleCreateAccount}
            class="slds-m-left_x-small"></lightning-button>
        <p slot="footer">This Component checks the CRUD in LWC. The Created Record Id is : {createdAccountId}</p>
        <p slot="footer">errors:- {error}</p>
    </lightning-card>
</template>

createAccounts.js

The js file has three property annonated with track along with two method named handleOnChange and handleCreateAccount. handleOnChange method will get the value of the name field input by user and store it in trackable property named accountName.

handleCreateAccount calls an apex method named createAccountRecord by passing the parameter imported at the beginning of js file. It also stores the return value and any error message if exist.

import { LightningElement, track } from 'lwc';
import createAccountRecord from '@salesforce/apex/checkCRUDForLWC.createAccountRecord';
export default class CreateAccounts extends LightningElement {
    @track accountName;
    @track createdAccountId;
    @track error;

    handleOnChange(event) {
        this.accountName = event.target.value;
    }
    handleCreateAccount() {
        createAccountRecord({ accName: this.accountName })
            .then(result => {
                if (result) {
                    this.createdAccountId = result.Id;
                    this.error = undefined;
                } else {
                    this.error = 'You dont have permission to create record';
                }
            })
            .catch(error => {
                this.error = error;
                this.createdAccountId = undefined;
            });
    }
}

createAccounts.js-meta.xml

The meta file defines the visibility and configuration of the lightning web component like where you can use the component in Salesforce.

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

We also have the apex method which is being called from js file of the lightning web component. It checks the current user access to create a record of a particular object.

checkCRUDForLWC.apxc

public class checkCRUDForLWC {
    @AuraEnabled
    public static Account createAccountRecord(string accName){
        Account acc = new Account();
        acc.name=accName;
        if(isCreateable('Account')==true){
            insert acc;
            return acc;
        }
        return null;
    }
    public static Boolean isCreateable(String sObjectType){
        SObjectType schemaType = Schema.getGlobalDescribe().get(sObjectType);
        return schemaType.getDescribe().isCreateable();
    }
}

The above class will run in system context. We have defined one additional method to check current user’s CRUD access on an object. We are calling it in insert method to check the CRUD access. If user has CRUD access, it will return true else it will return false.

Demo

LIghtning Web Component Best Practise

Summary(Do LWC respect CRUD Access in apex method?)

As a developer, We should always check the CRUD access when we are invoking a Apex method through Lightning Web Component. This blog focused on does Lightning Web Component respect the CRUD access in apex method while creating a record, I will highlight the Read, update and delete access check in upcoming blogs.

One comment

  1. Hi,

    Why can’t we achieve this by changing the Apex method, by adding keyword ‘with sharing’ in the Controller.

    I am having a query, in ‘lightning/uiRecordApi’ library we have a method, ‘createRecord’. This method, respects User’s CRUD access. It is throwing error while I try updating a field which doesn’t have edit access.
    Is there any way to run this method in System Context.

Leave a Reply