Skip to Content
Personal Insights
Author's profile photo Pritesh Patel

SAPUI5 & SAP Fiori:Barcode or QR code scanning in SAPUI5 applications.

Hello Everyone!

In this blog I will demonstrate how a device camera can be accessed within a SAPUI5 application to scan a barcode and populate the value of the barcode into an input field. This will be achieved in a plain SAPUI5 web application which can be accessed via any device that has a camera and a supported browser (we will implement a fallback solution when the application is accessed via a desktop or device with no camera). We will make use of an external JavaScript library called cordova plugin which will handle the detection and decoding of barcodes.

This is a step by step tutorial showing how to use your device camera as a barcode scanner in  SAPUI5  App with SAP Web IDE.We make use of cordova barcode scanner plugin.This plugin enables to scan and decode a barcode using the device camera.The plugin support android and ios platforms.

This code for Employee Attendance . In this code, When any id card scaned  by Employee at that time data checked in backend and display data in table.

 

Pre-requisites

  1. Knowldge of UI5,Javascript,xml
  2. Created basic SAPUI5 Application

 

More information about the Cordova Barcode Scanner can be found here:

Build SAPUI5 Cordova Barcode Scanner with OData Service

Steps

Create Ui5 app and write this code in XML file this xml file include button for scan  and table.that table displday scaned data.

<core:View xmlns:core="sap.ui.core" xmlns:mvc="sap.ui.core.mvc" xmlns="sap.m" controllerName="qrcode.qrcode.controller.View1"
xmlns:html="http://www.w3.org/1999/xhtml">
<App id="app">
	<pages>
	<Page id="page" title="Employee Attendance">
		<content>
		      <Button text="Scan" press="onBarcodeScan" icon="sap-icon://bar-code"/>
			<Panel backgroundDesign="Transparent">
					<Table id="Employee" items="{/daf_empattSet}">
					<headerToolbar>
					<Toolbar>
					<Title text="{i18n>Employee Attendence Details}"/>
					<ToolbarSpacer/>
					<SearchField placeholder="Search By Name" width="50%" liveChange="onFilterInvoices1" search="onFilterInvoices"/>
					</Toolbar>
					</headerToolbar>
					<items>
					<ColumnListItem>
					<cells>
					<Text text="{Srno}"></Text>
					<Text text="{Dinkid}"></Text>
			<Text text="{path: 'Tdate', type:'sap.ui.model.type.Date', formatOptions : { pattern:'dd.MM.yyyy'}}"/>
			<Text text="{path: 'Entrytime', type:'sap.ui.model.odata.type.Time', formatOptions: {pattern: 'HH:mm:ss'}}"/>
			<Text text="{path: 'Exittime', type:'sap.ui.model.odata.type.Time', formatOptions: {pattern: 'HH:mm:ss'}}"/>
		 	      <Text text="{path: 'Totalhrs', type:'sap.ui.model.odata.type.Time', formatOptions: {pattern: 'HH:mm:ss'}}"/>
					<Text text="{Latehrs}"></Text>
					</cells>
					</ColumnListItem>
					</items>
					<columns>
						<Column>
							<Text text="Srno"></Text>
						</Column>
						<Column>
							<Text id="Dinkid" text="Dinkid"></Text>
						</Column>
						<Column>
							<Text text="Date"></Text>
						</Column>
						<Column>
							<Text id="Entrytime1" text="In Time"></Text>
						</Column>
						<Column>
							<Text id="Exittime2" text="Out Time"></Text>
						</Column>
						<Column>
							<Text text="Total Hours"></Text>
						</Column>
						<Column>
							<Text id="Latehrs3" text="Latehrs"></Text>
						</Column>
					        </columns>
						</Table>
					</Panel>
				</content>
			</Page>
		</pages>
	</App>
</core:View>

write below code in controller.

The onbarcodescan method performs the barcode scanning. It is calling the cordova plugin barcodeScanner to get the barcode detail in result.text. Then pass this  to the OData query string to perform the OData query. The response  will be captured and printed in the scanresult page.    Update model method used for update data in backend, and other two method used for search and display Employee data.

sap.ui.define([
	"sap/ui/core/mvc/Controller",
	"sap/ndc/BarcodeScanner",
	"sap/ui/model/Filter",
	"sap/ui/model/FilterOperator"

], function (Controller, BarcodeScanner, Filter, FilterOperator) {
	"use strict";
	var ServiceUrl = "";
	var oModel = new sap.ui.model.odata.ODataModel(ServiceUrl);
	return Controller.extend("qrcode.qrcode.controller.View1", {

		onInit: function () {

		},

		onBarcodeScan: function () {
			var dinkid;
			var that = this;
			var code = "";
			if (!cordova.plugins.barcodeScanner) {
				alert("Barcode scanning not supported");
				return;
			}
			cordova.plugins.barcodeScanner.scan(
				function (result) {
					if (result.format == "QR_CODE") {
					
						code = result.text;
						dinkid = result.text.split(" ")[2];
						oModel.read("/daf_empmasterSet", null, null, true, function (oData, response) {
						

							for (var i = 0; i < response.data.results.length; i++) {
								var mdinkid = response.data.results[i].Dinkid;
								if (dinkid === mdinkid) {
									var Srno1 = response.data.results[i].Srno;
									var Dinkid1 = response.data.results[i].Dinkid;
									that.updateModel(Srno1, Dinkid1);
								}
							}

						});

						that.getView().byId("searchField").setValue(code);
						that.onSearch();
					}
				},
				function (error) {
					alert("Scan failed: " + error);
				},

				{
					preferFrontCamera: true, // iOS and Android
					showFlipCameraButton: true, // iOS and Android
					showTorchButton: true, // iOS and Android
					torchOn: true, // Android, launch with the torch switched on (if available)
					saveHistory: true, // Android, save scan history (default false)
					prompt: "Place a barcode inside the scan area", // Android
					resultDisplayDuration: 500, // Android, display scanned text for X ms. 0 suppresses it entirely, default 1500
					formats: "QR_CODE,PDF_417", // default: all but PDF_417 and RSS_EXPANDED
					orientation: "landscape", // Android only (portrait|landscape), default unset so it rotates with the device
					disableAnimations: true, // iOS
					disableSuccessBeep: false // iOS and Android
				}
			);
		},
		updateModel: function (Srno1, Dinkid1) {
			var oTable = this.byId("Employee");
			var Tdate = new Date();
			var dateFormat = sap.ui.core.format.DateFormat.getInstance({

				pattern: "yyyy-MM-ddThh:mm:ss"
			});
			var Tdate1 = dateFormat.format(new Date(Tdate));

		

			/*	var EntryTime1 = Tdate.toTimeString().split(" ")[0];
			var tdateFormat = sap.ui.model.odata.type.Time({

			pattern: "HH:mm:ss"
			});
			var EntryTime = tdateFormat.format(Tdate);*/

			var timeFormat = sap.ui.core.format.DateFormat.getTimeInstance({
				pattern: "'PT'HH'H'mm'M'ss'S'"
			});

			var EntryTime = timeFormat.format(Tdate);

			var oEntry = {
				"Srno": Srno1,
				"Dinkid": Dinkid1,
				"Tdate": Tdate1,
				"Entrytime": EntryTime,
				"Exittime": EntryTime,
				//	"Totalhrs": EntryTime,
				"Latehrs": "X"
			};

			oModel.update("/daf_empattSet(Srno='" + Srno1 + "')",
				oEntry, {
					method: "PUT",
					success: function (oData, oResponse) {
					
						oTable.getModel().refresh();
						oTable.getBinding("items").refresh(true);
						sap.m.MessageToast.show("Successfully Scanned");
					},
					error: function (err, oResponse) {

						sap.m.MessageToast.show("Somthing is Wrong.");

					}
				});
		},

		onFilterInvoices: function (oEvent) {
		

			// build filter array
			var aFilter = [];
			var sQuery = oEvent.getParameter("query").toUpperCase();
			if (sQuery) {
				aFilter.push(new Filter("Dinkid", FilterOperator.Contains, sQuery));
			}

			// filter binding
			var oList = this.getView().byId("Employee");
			var oBinding = oList.getBinding("items");
			oBinding.filter(aFilter);
		},
		onFilterInvoices1: function (oEvent) {
		

			// build filter array
			var aFilter = [];
			var sQuery = oEvent.getParameters().newValue.toUpperCase();
			if (sQuery) {
				aFilter.push(new Filter("Dinkid", FilterOperator.Contains, sQuery));
			}

			// filter binding
			var oList = this.getView().byId("Employee");
			var oBinding = oList.getBinding("items");
			oBinding.filter(aFilter);
		}
	});
});​

 

when you run your application your application look like below

 

if you face any kind of issues executing these steps kindly comment it down here and give me your valueble feedback regarding this blog post ,I am always ready to help!!

Thanks for reading!

Assigned tags

      13 Comments
      You must be Logged on to comment or reply to a post.
      Author's profile photo Sagar Salyan
      Sagar Salyan

      Hi Pritesh,

       

      Thanks for sharing, I have one question, how to add Cordova plugins to sap ui5 web app from webide.

       

      Thanks

      Author's profile photo Pritesh Patel
      Pritesh Patel
      Blog Post Author

      Hey sagar

      As per your issue
      Do below step to add cordova plugin
      Right-click on the project and in the context menu, select Mobile > Select Cordova Plugins > Kapsel. Find the kapsel-plugin-barcodescanner and unselect it. Save your changes. Our Cloud Build Service will pick up custom plugins from a folder called plugins in the mobile folder of your project.

       

      Author's profile photo Robin van den Brandt
      Robin van den Brandt

      does this work for deploy to on-premise as well?

      Author's profile photo Adi Mogilevsky
      Adi Mogilevsky

      Nice one. I will walk through by morning

      Author's profile photo Pritesh Patel
      Pritesh Patel
      Blog Post Author

      Hello sir,

      Thank you for your valuable time.

       

       

      Author's profile photo Robin van den Brandt
      Robin van den Brandt

      Hi Pritesh,

       

      Does it work for apps that are deployed to an onPremise server and then launched via FLP in Safari on a mobile device? Or should the app be launched via Fiori Client (to get Cordova plugins) on mobile devices?

       

      Thanks,

       

      Robin

      Author's profile photo Pritesh Patel
      Pritesh Patel
      Blog Post Author

      hey @Robin van den Brand

      I have tested this application on the SAP Fiori Client app and it's working fine. and

      it works for apps that are deployed to the Cloud Platform. but I don't check for an On-premise server.

       

      Regards

       

      Pritesh Patel

      Author's profile photo Robin van den Brandt
      Robin van den Brandt

      Hi Pritesh,

      The Cordova plugins are embedded into the SAP Fiori Client so this works for apps deployed to the cloud platform as well as for on-premise apps.

      My requirement is to get the Cordova plugin working in on-premise apps launched via browser on mobile devices (so without using the SAP Fiori Client and without using external JS barcode libraries)...

      Any idea on how to fulfill this requirement?

      Regards,

      Robin

       

       

      Author's profile photo Pritesh Patel
      Pritesh Patel
      Blog Post Author

      Hi Robin,

      I have not any idea about your requirement. if I have got any idea about this sure I will update you.

       

      regards

      Pritesh

      Author's profile photo R. Van Den Brandt
      R. Van Den Brandt

      Hi Pritesh,

       

      Thanks for your prompt response. My requirement is to embed Cordova plugins into custom apps deployed to on-premise server.

      FYI: Cordova barcode scanner is embedded in some custom apps but the barcode scanner only works when the app is launched via SAP Fiori client. If the Cordova plugins could be embedded in the app itself then the barcode scan might work via direct browser access (without using SAP Fiori client and without changing the code to use an external JS library) .

       

      Regards,

       

      Robin

      Author's profile photo Anugrah George James
      Anugrah George James

      Hi Robin,

      This link might be helpful to you regarding your requirement.

      https://blogs.sap.com/2021/02/01/native-js-zxing-scanner-in-sapui5/

       

      Regards,

      Anugrah

      Author's profile photo R. Van Den Brandt
      R. Van Den Brandt

      Hi Anugrah,

       

      I will do some more research but at first glance this seems to be a solid option to fulfill my requirement, many thanks!!

       

      Regards,

      Robin

      Author's profile photo Archit Parikh
      Archit Parikh

      Great work!!