How to use the getUserPrivilege function in Dataverse Client API

The getUserPrivilege is a function that will return canReadcanCreate, and canUpdate. This function correlated with the Field Level Security feature making it suitable to check if users have enough privilege to run our custom function on Javascript.

For example, we have below customization on formOnLoad:

var BlogJs = BlogJs || {};
(function() {
    this.formOnLoad = function(executionContext){
        onLoadCustomerId(executionContext);
        setValueIcNumber(executionContext);
    };

    var onLoadCustomerId = function(executionContext){
        var formContext = executionContext.getFormContext();
        // formOnLoad logic for CustomerId attribute (enabled Field Level Security)
        // Can be init value, addPreSearch, etc..
        console.log("onLoadCustomerId called!");
    };

    var setValueIcNumber = function(executionContext){
        var formContext = executionContext.getFormContext();
        formContext.getAttribute("twr_icnumber").setValue("temmy-testing");
    }
}).apply(BlogJs);

In the example above, let’s say we already set up the CustomerId and IC Number attribute to be part of Field Level Security. But, we have custom logic for both of the attributes that lead to some users not having enough access. So, to fix it we can use the getUserPrivilege function:

var BlogJs = BlogJs || {};
(function() {
    this.formOnLoad = function(executionContext){
        onLoadCustomerId(executionContext);
        setValueIcNumber(executionContext);
    };

    var onLoadCustomerId = function(executionContext){
        var formContext = executionContext.getFormContext();
        // if user can't create, return
        if(!formContext.getAttribute("twr_customerid").getUserPrivilege().canCreate) return;
        // formOnLoad logic for CustomerId attribute (enabled Field Level Security)
        // Can be init value, addPreSearch, etc..
        console.log("onLoadCustomerId called!");
    };

    var setValueIcNumber = function(executionContext){
        var formContext = executionContext.getFormContext();
         // if user can't create, return
         if(!formContext.getAttribute("twr_customerid").getUserPrivilege().canCreate) return;
         
        formContext.getAttribute("twr_icnumber").setValue("temmy-testing");
    }
}).apply(BlogJs);

If the user doesn’t have enough access to the CustomerId attribute (for Read, Create, or Update), we don’t need to run the logic (to avoid error)!

Happy CRM-ing!

Author: temmyraharjo

Microsoft Dynamics 365 Technical Consultant, KL Power Platform User Community Leader, Student Forever, Test Driven Development, and Human Code enthusiast.

One thought on “How to use the getUserPrivilege function in Dataverse Client API”

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.