how to hide a view based on condition

Gopal14
Tera Contributor

Hi Team, how to hide a view based on condition.

I have created a view, I want to show that view only for group "HPC View group".

Below is my view rule script:

var currentUser = gs.getUser(); // Check if the current user is a member of the 'HPC View' group

if (currentUser.isMemberOf('HPC View group'))

{

// If the user is a member of the group, set the answer variable to 'HPC View'

var answer = "HPC View"; }

else { // If the user is not a member of the group, you might want to handle this case accordingly

var answer = "Not HPC View"; }

 

Script is not working, Can any one help

 

@Community Alums 

9 REPLIES 9

Abhishek Kathe
Mega Guru

It seems like you're trying to conditionally control the visibility of a view in ServiceNow based on whether the current user is a member of a specific group. Here's how you can achieve this:

Navigate to the view you want to control the visibility of.
Under the view configuration, find the "View Rules" section.
Create a new view rule.
In the script field, you can use the following script:
javascript
Copy code
// Check if the current user is a member of the 'HPC View' group
if (gs.hasRole('HPC View group')) {
// If the user is a member of the group, return true to show the view
answer = true;
} else {
// If the user is not a member of the group, return false to hide the view
answer = false;
}
Make sure to replace 'HPC View group' with the actual name of the group you want to check for membership.

Hi @Abhishek Kathe 

 

Can I use below code:

 

if (gs.hasRole('HPC View group')) {
// If the user is a member of the group, return true to show the view
answer = true;
} else {
// If the user is not a member of the group, return false to hide the view
answer = false;
}

Community Alums
Not applicable

Yes , it should work.

 

Yes

Community Alums
Not applicable

Hi @Gopal14 ,

I tried your problem in my PDI and it works for me please refer below steps 

Create New View Rule and fill the form like below image 

SarthakKashyap_0-1715762426257.png

(function overrideView(view, is_list) {

    // Add your code here
    // answer = null;  // set the new view to answer
	gs.log("here in view rule - " + gs.getUser().isMemberOf('Software'));
	
    if (gs.getUser().isMemberOf('Software')) {
		gs.log('Inside if View Rule');
        answer = "test_sarthak"; // Add your view Name
    } else {
		gs.log('Inside Else View Rule');
        answer = "Default"; // // Add your view Name
    }

})(view, is_list);

 

As I'm member of software group I checked from Group table 

SarthakKashyap_1-1715762500948.png

 

So Incident form opens for me in test_sarthak demo view 

SarthakKashyap_2-1715762548300.png

 

If I remove my self from software group than it opens from me default view

SarthakKashyap_3-1715762612747.png

 

Please mark my answer correct and helpful if this works for you

Thanks and Regards 

Sarthak