← Script library

Client Scripts

Role-based Section/Field Visibility

Show or hide sections or specific fields based on the current user's roles, useful for restricting sensitive information access.

JavaScript
function onLoad() {
  // Configuration: Define visibility rules based on roles
  // Key = role name, Value = object with sections and fields to show
  var roleVisibilityMap = {
    'itil': {
      sections: ['closure_info', 'resolution_info'],
      fields: ['close_code', 'close_notes', 'resolved_by', 'resolved_at']
    },
    'security_admin': {
      sections: ['security_info'],
      fields: ['u_security_classification', 'u_compliance_notes', 'u_data_breach']
    },
    'financial_user': {
      sections: ['cost_info'],
      fields: ['u_estimated_cost', 'u_actual_cost', 'u_billing_code']
    }
  };

  // Get current user's roles
  var userRoles = g_user.getRoles().split(',');

  // Determine which sections/fields to show
  var sectionsToShow = [];
  var fieldsToShow = [];

  // Check each role
  userRoles.forEach(function(role) {
    if (roleVisibilityMap[role]) {
      // Add sections for this role
      if (roleVisibilityMap[role].sections) {
        sectionsToShow = sectionsToShow.concat(roleVisibilityMap[role].sections);
      }
      // Add fields for this role
      if (roleVisibilityMap[role].fields) {
        fieldsToShow = fieldsToShow.concat(roleVisibilityMap[role].fields);
      }
    }
  });

  // Hide all configured sections first
  Object.keys(roleVisibilityMap).forEach(function(role) {
    if (roleVisibilityMap[role].sections) {
      roleVisibilityMap[role].sections.forEach(function(section) {
        g_form.setSectionDisplay(section, false);
      });
    }
    if (roleVisibilityMap[role].fields) {
      roleVisibilityMap[role].fields.forEach(function(field) {
        g_form.setDisplay(field, false);
      });
    }
  });

  // Show only sections/fields user has access to
  sectionsToShow.forEach(function(section) {
    g_form.setSectionDisplay(section, true);
  });

  fieldsToShow.forEach(function(field) {
    g_form.setDisplay(field, true);
  });

  // Optional: Add info message if restricted content is hidden
  if (sectionsToShow.length === 0 && fieldsToShow.length === 0) {
    // Check if any restrictions apply
    var hasRestrictions = Object.keys(roleVisibilityMap).length > 0;
    if (hasRestrictions) {
      g_form.addInfoMessage('Some fields are hidden based on your role permissions.');
    }
  }
}

How to use it

1. Create an onLoad Client Script on your table 2. Customize the `roleVisibilityMap` object with your roles and fields/sections 3. Ensure section names match your form layout 4. Test with users having different role combinations 5. Consider adding sys_admin to bypass all restrictions if needed 6. Document which roles can see which sections for governance

Adapt the table names, fields, and conditions to your instance. Test the behavior in a development environment before using it in production.