Technology Blog Posts by Members
Explore a vibrant mix of technical expertise, industry insights, and tech buzz in member blogs covering SAP products, technology, and events. Get in the mix!
cancel
Showing results for 
Search instead for 
Did you mean: 
RanishreeBV25
Explorer
491

Implementing User Role-Based Views in SAPUI5: A Complete Guide

Introduction

In today's enterprise application development, delivering the right experience to the right users is just as crucial as the functionality itself. One of the most effective ways to achieve this is through role-based view management - a powerful approach that tailors the user interface based on individual permissions and responsibilities.

I'm excited to share this comprehensive guide on implementing role-based views in SAPUI5 applications. Whether you're building a new application from scratch or enhancing an existing one, implementing proper view segregation will not only improve security but also create a more focused and efficient user experience.

In this blog, we'll explore:

  • The critical importance of role-based views in enterprise applications
  • A step-by-step implementation guide using SAPUI5's powerful features
  • How to combine OData services with dynamic UI controls
  • Professional best practices refined from real-world implementations

By the end of this guide, you'll be able to create applications where:

  • Administrators (ADMN) have complete system access
  • Project Managers (PM) see management-relevant views
  • Team Leads (TL) access team coordination features
  • Regular Employees (RE) work with task-specific interfaces

Let's transform your SAPUI5 application into a secure, role-appropriate experience that users will appreciate!

Why Role-Based Views Matter More Than Ever

In our increasingly security-conscious digital landscape, role-based views provide three fundamental benefits:

  1. Security Through Obscurity
    By completely hiding unauthorized functionality rather than just disabling it, we eliminate potential attack vectors and accidental access to sensitive operations.
  2. Cognitive Simplicity
    Users aren't distracted by irrelevant menu items or functions they can't use, leading to higher productivity and satisfaction.
  3. Compliance Ready
    Many industry regulations (GDPR, SOX, HIPAA) explicitly require proper access controls that role-based views help implement.

Prerequisites for Implementation

Before we begin, you'll need:

✔ SAPUI5 Fundamentals - Comfort with MVC concepts and data binding
✔ Development Environment - SAP Business Application Studio or local IDE setup
✔ Backend Access - OData service with employee data (mock data works for testing)
✔ Basic Security Understanding - Familiarity with authentication flows

 

Let's begin our journey to create a truly professional role-based SAPUI5 application!

Project Structure

RanishreeBV25_0-1745835614130.png

 

Data

RanishreeBV25_1-1745837442210.png

 

Step 1: Set Up the Login System

Login Controller (Login.controller.js)

 onInit() {
            var oComponentModel = this.getOwnerComponent().getModel();
            var oModel = this.getOwnerComponent().getModel('employeesModel')
            oComponentModel.read("/your_entitySetName",{
                  method:'GET',
                  success: function (oData, response){
                  oModel.setProperty('/employees',oData.results)
                  },
  
                  error: function(error){
                      console.error("Error Loading Data: " + error);
                  },
              
              });  
        },
onPressLoginBtn: function() {
  const sUsername = this.byId("name").getValue();
  const sPassword = this.byId("userId").getValue();
  
  const oModel = this.getOwnerComponent().getModel("employeesModel");
  const aEmployees = oModel.getProperty("/employees") || [];
  
  const oEmployee = aEmployees.find(emp => 
    emp.UserId === sUsername && emp.Password === sPassword
  );
  
  if (oEmployee) {
    oModel.setProperty("/currentUser", oEmployee); // Store user data
    this.getOwnerComponent().getRouter().navTo("MainView");
  } else {
    sap.m.MessageToast.show("Invalid credentials");
  }
}


Key Points:

  • Validates credentials against fetched employee data.
  • Stores the logged-in user in employees Model.

Login View(Login.view.xml)

<VBox justifyContent="Center" alignItems="Center" height="100%">
                <Panel width="430px" class="loginFormPanel">
                    <form:SimpleForm title="Login Here" class="sapUiMediumMarginTopBottom">
                        <Label></Label>
                        <Input id="name" placeholder="Enter Name"></Input>
                        <Label></Label>
                        <Input id="userId" placeholder="Enter UserId" type="Password"></Input>
                        <Label></Label>
                        <Button text="Login" press="onPressLoginBtn" type="Emphasized"></Button>
                    </form:SimpleForm>
                </Panel>
            </VBox>

Main View(Main.view.xml)

<core:Fragment fragmentName="roleassignment.fragments.IconTabBar" type="XML"></core:Fragment>

IconTabBar Fragment (IconTabBar.fragment.xml)

  <IconTabBar id="idIconTabBar" expandable="false" headerMode="Inline">
        <items>
            <IconTabFilter text="Roles" key="roles"> 
                <mvc:View viewName="roleassignment.view.subView.AllRole" type="XML"></mvc:View>
                    <items>
                        <IconTabFilter text="AdminView" key="AdminView" visible="{= ${employeesModel>/currentUser/Role} === 'ADM' }">
                            <mvc:View viewName="roleassignment.view.subView.Admin" type="XML"/>
                        </IconTabFilter>
                        <IconTabFilter text="ProjectManagerView" key="ProjectManagerView"  visible="{= ${employeesModel>/currentUser/Role} === 'ADM' || ${employeesModel>/currentUser/Role} === 'PM' }">
                            <mvc:View viewName="roleassignment.view.subView.ProjectManager" type="XML"/>
                        </IconTabFilter>
                        <IconTabFilter text="TeamLeadView" key="TeamLeadView"  visible="{= ${employeesModel>/currentUser/Role} === 'ADM' || ${employeesModel>/currentUser/Role} === 'PM' || ${employeesModel>/currentUser/Role} === 'TL' }">
                            <mvc:View viewName="roleassignment.view.subView.TeamLead" type="XML"/>
                        </IconTabFilter>
                        <IconTabFilter text="RegularEmpView" key="RegularEmpView" >
                            <mvc:View viewName="roleassignment.view.subView.RegularEmp" type="XML"/>
                        </IconTabFilter>
                    </items>
            </IconTabFilter>
        </items>
    </IconTabBar>

AllRole View(AllRole.view.xml)

<Table   >
	<columns>
		<Column >
			<Text text="ID"></Text>
		</Column>
		<Column >
			<Text text="Name"></Text>
		</Column>
		<Column >
			<Text text="Role Description"></Text>
		</Column>
	</columns>
	<items>
		<ColumnListItem>
			<cells>
				<Text text="{employeesModel>/currentUser/Id}"></Text>
				<Text text="{employeesModel>/currentUser/Name}"></Text>
				<Text text="{employeesModel>/currentUser/Roledescription}"></Text>
			</cells>
		</ColumnListItem>
	</items>
</Table>

Admin View(Admin.view.xml)

	<c:Fragment fragmentName="roleassignment.fragments.tables.Admin" type="XML"></c:Fragment>

Admin Fragment(Admin.fragment.xml)

<Table items="{employeesModel>/ADMData}">
        <columns>
            <Column>
                <Text text="ID"></Text>
            </Column>
            <Column>
                <Text text="Name"></Text>
            </Column>
            <Column>
                <Text text="Role"></Text>
            </Column>
            <Column>
                <Text text="Role Description"></Text>
            </Column>
        </columns>
        <items>
            <ColumnListItem >
                <cells>
                    <Text text="{employeesModel>Id}"></Text>
                    <Text text="{employeesModel>Name}"></Text>
                    <Text text="{employeesModel>Role}"></Text>
                    <Text text="{employeesModel>Roledescription}"></Text>

                </cells>
            </ColumnListItem>
        </items>
    </Table>

Admin Controller (Admin.controller.js)

var oComponentModel = this.getOwnerComponent().getModel();
			var oModel = this.getOwnerComponent().getModel('employeesModel')
			oComponentModel.read("/Your_entitySetName",{
				  method:'GET',
				  urlParameters: {
					  "$filter": "Role eq 'ADM'"
				  },
				  success: function (oData, response){
				  oModel.setProperty('/ADMData',oData.results)
				  },
				  error: function(error){
					  console.error("Error Loading Data: " + error);
				  },
			  
			  });  	

How It Works:

  • Binds visibility to the user’s role.
  • Only shows tabs matching the user’s permissions.

 

Other Views

  • ProjectManager.view.xml

  • TeamLead.view.xml

  • RegularEmp.view.xml

Other Controllers

  • ProjectManager.controller.js

  • TeamLead.controller.js

  • RegularEmp.controller.js.

The implementation follows a consistent pattern where only the fragment names differ based on roles. Here's how to adapt the same logic across all views:

  1. Fragment Naming Structure

    • Each role has its own fragment file following this naming pattern:

      • Admin.fragment.xml

      • ProjectManager.fragment.xml

      • TeamLead.fragment.xml

      • RegularEmp.fragment.xml

  2. Identical Implementation Logic
    While the fragment names are different, they all share:

    • The same table structure and column layout

    • The same type of data bindings

    • The same controller approach for data loading

  3. How to Apply This Pattern
    For each role view:

    • Create a new fragment file with the role-specific name

    • Copy the same table structure from existing fragments

    • Only change:

      1. The binding path to match the role (PMData/TLData/REData)

      2. The filter condition in controller ("Role eq 'PM'" etc.).

UI Output Screenshots

image.png

image.png

Administrator sees all available tabs

 

 

 

image.pngimage.png

Project Manager access with PM/TL/RE tabs (Admin tab hidden)

 

 

image.pngimage.png

Single-tab interface for regular employees.

 

Key Visual Differentiators

  1. Role-Specific Tab Visibility

    • Admin: 4 tabs visible

    • PM: 3 tabs visible

    • TL: 2 tabs visible

    • RE: 1 tab visible

  2. Data Columns
    Same structure across all fragments, with:

    • ID, Name, Role, Role Description fields

    • Color-coded by role (admin=red, pm=blue, tl=green, re=grey)

  3. Visual Cues

    • Role badge in header

    • Disabled/hidden elements for unauthorized actions

    • Consistent table styling across fragments.

 

Conclusion

By leveraging SAPUI5’s binding and OData capabilities, we built a secure, role-based navigation system that:
✔ Restricts views based on roles
✔ Optimizes data loading
✔ Scales easily for new roles.

I hope you found this guide helpful! If you have any questions or feedback, feel free to leave a comment below. Happy coding!