Technology Blogs 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: 
lvanderzande
Explorer
The SAPUI5 Barcode Scanner can be used to scan bar codes using the device's camera.

In recent versions of the SAPUI5 Library, the Barcode Scanner component allowed for non-native device based camera access. (We can use Barcode Scanner in our desktop browser!)

Through using an Input's valueHelpRequest as the trigger for the BarcodeScanner.scan function, we are able to allow for both manual input and ease of access to the scanning feature.

With some abstraction thrown into the mix, we get a reusable function which can be used on any input field.
<Input 
id="barcodeScannerInput"
type="Text"
value="{/BarCode}"
valueHelpRequest="openScannerForInput('barcodeScannerInput', 'barcodeScannerInputCallback')"
valueHelpIconSrc="sap-icon://bar-code"
showValueHelp="true"
/>

The openScannerForInput function takes two arguments, the id of the input which should have it's value replaced with the scanned value, and an optional callback function name.
/**
* Open Scanner Input is called from inside the View
*/
openScannerForInput(input, callback) {
this._openScannerForInput(this.getView(), input, callback)
}

/**
* Helper function for openScannerInput
* receives an extra parameter for the current view that is calling the function
*/
_openScannerForInput(view, input, callback) {
if (typeof input === 'string') {
input = view.byId(input)
}
// https://sapui5.hana.ondemand.com/#/api/sap.ndc.BarcodeScanner%23methods/sap.ndc.BarcodeScanner.scan
sap.ndc.BarcodeScanner.scan((data) => {
const barcode = data.text
if (barcode) {
sap.m.MessageToast.show(" Barcode Detected " + barcode)
input.setValue(barcode)
if (callback) view.getController()[callback](barcode)
}
}, undefined, undefined, undefined, undefined, undefined, 1, false)
}

Both of these functions are stored on a BaseController which all of my controllers will extend to have access to this functionality.

Here is the callback example which could be used in a child controller.
barcodeScannerInputCallback(code) {
var oModel = this.getView().getModel();
//handle extra logic for when barcode is scanned for an input here
this.getOwnerComponent().getModel("ODataBackend").read(
// the `code` parameter and the `/BarCode` property on our model will be the same
// `/BarCodeEntitySet('${oModel.getProperty("/BarCode")}')`
`/BarCodeEntitySet('${code}')`,
{
success: (oData, oResponse) => {
.setProperty("/BarCodeEntitySet", oData)
},
error: (oData, oResponse) => {
console.error(error)
}
}
)
}


Thank you for reading!
1 Comment
Labels in this area