Change form view using switchview if user has a specific role using client script.

Mycena Jane Cam
Tera Contributor

Please help I'm trying to change the view of the form using switchview in client script if user has a role please see below..

find_real_file.png

find_real_file.png

4 REPLIES 4

palanikumar
Mega Sage

Hi,

If your requirement is to set default view for a specific role then I suggest you to create View Rule. Follow the below steps

1) Navigate to System UI > View Rules
2) Click New button
3) Set following values
Name : Some meaningful name
Table : <your table name>
Advanced : Checked
Script: (Update the view name and role name with actual values

(function overrideView(view, is_list) {
	if (gs.hasRole("<type the role name>")) {
		answer = "<type the view name>";  // set the new view to answer
		return;
	}
	answer = view;
})(view, is_list);
Thank you,
Palani

anandthallapure
Tera Contributor

Hi Palani,

 

Mentioned view going to applicable for admin also.

When I used gs.hasRoleExactly the view is not applying at all.

When I used gs.hasRole view going to be applicable for intended user as well as admin.

Please help me.

DK44
Tera Expert

Hello,

Please check this script for reference.
I have used it in a UI Policy that has no conditions and it is working on the incidents table.
Generally what it does is if the view is not default and if the user is not admin, it sets is as the default and informs the user.

View Rules do not work in order to restrict users not to use other views. 
View Rules are triggered only when you select the default view in the view changer.
Also if you do not use the advanced option in a View Rule it hides the Vie Changer option and uses the view that is set in the view rule but it does not do the same when you use the advanced condition.

Im using a UI Policy since I determined that the work faster than client scripts.

function onCondition() {
    var viewName = getParmVal('sysparm_view');

    if ((viewName != '' && viewName != undefined) && !g_user.hasRoleExactly('admin')) {
        switchView('section', 'incident', ''); // Incident is the current specified table so ammend this to the table you want to use.
        g_form.addInfoMessage('The selected view is available only to admin users, reverting to default view.');
    } else {
        return;
    }

    function getParmVal(name) {
        var url = top.location.href;
        var value = new URLSearchParams(url).get(name);
        if (value) {
            return value;
        }
        if (!value) {
            var gUrl = new GlideURL();
            gUrl.setFromCurrent();
            value = gUrl.getParam(name);
            return value;
        }
    }
}



Great solution, had tried to force users to default view via view rules. Never worked.
Thanks a lot for this!