June 18, 2015

Hide fields dynamically based on Field Level Security privileges

When we set up Field Level Security for a field we can assign three different privileges (Read, Update, Write) to the users.
It is also possible to check the privilege using a supported JavaScript method: getUserPrivilege
This method returns an object with three boolean properties: canRead, canUpdate, canCreate.

We can use these properties in combination with the forEach method of attributes and controls collections in order to dynamically hide the fields.

The following code will hide dynamically all the fields protected by Field Level Security that the user can't read:
function HideSecuredFields() {
    // fetch all attributes on the form
    Xrm.Page.data.entity.attributes.forEach(
        function(attribute, aIndex) {
            // get the FLS privileges
            var privileges = attribute.getUserPrivilege();
            // check if the user can't read the field
            if (privileges.canRead == false) {
                // fetch all the controls related to the attribute
                attribute.controls.forEach(
                    function (control, cIndex) {
                       // hide the controls
                       control.setVisible(false);
                    }
                );
            }
        }
    );
}

0 comments:

Post a Comment