Reusable SAPUI5 Barcode Scanner Input Value Help
2023-12-15 05:26:23 Author: blogs.sap.com(查看原文) 阅读量:6 收藏

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](code)
    }
  }, 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!


文章来源: https://blogs.sap.com/2023/12/14/reusable-sapui5-barcode-scanner-input-value-help/
如有侵权请联系:admin#unsafe.sh