Skip to Content
Technical Articles
Author's profile photo Nadya Brown

JavaScript with SAPUI5. Tips and Techniques for beginners. #2.

SAPUI5 is a JavaScript UI Framework. JavaScript is essential to develop SAPUI5 applications.

In my blog series I am sharing with you some small but very useful techniques that can be used by almost any developer.

At this post I will talk about math in JavaScript — how we can use the JS methods to calculate numbers and to do our coding.

 

Exercise 2.1. Useful Number method.

 

Sometimes a number that is stored as a string type, could be an issue to perform calculations. There is a way to solve this problem — passing the string value into the Number() constructor to return a number version of the same value.

Let’s assume that we need to create a mini app which will help us to calculate the total price of the products.

 

Mini calculator will look as follows:

 

Task: Create a SAPUI5 application which contains a Table and a Button items. Table has the Product name and Product price input fields. Button will show the total price of the products.

Step 1.

 

In XML view file add Table and Button item controls :

<Table headerText="Products data" class="sapUiMediumMargin">
	<columns>
		<Column>
			<header>
				<Text text="Items"></Text>
			</header>
			<footer>
				<Text text="Total"></Text>
			</footer>
		</Column>
		<Column>
			<header>
				<Text text="Price"></Text>
			</header>
			<footer>
				<Text id="total"></Text>
			</footer>
		</Column>
	</columns>
	<items>
		<ColumnListItem>
			<cells>
				<Text text="Item1"></Text>
				<Input id="input1" type="Number"></Input>
			</cells>
		</ColumnListItem>
		<ColumnListItem>
			<cells>
				<Text text="Item2"></Text>
				<Input id="input2" type="Number"></Input>
			</cells>
		</ColumnListItem>
	</items>
</Table>
<Bar>
<contentMiddle>
<Button text="Calculate" icon="sap-icon://simulate" press="calculate" class="sapUiLargeMargin"></Button>
</contentMiddle>
</Bar>

Step 2.

 

In controller.js activate the Calculate button and complete a function using Number() method.

Sample of the code below:

calculate: function () {
			var item1Value = this.getView().byId("input1").getValue();
			var item2Value = this.getView().byId("input2").getValue();
			var total = Number(item1Value) + Number(item2Value);
			this.getView().byId("total").setText(total);
		},

 

Mini calculator will look as follows after the code is complete:

 

Exercise 2.1. Array method.

 

Now let’s assume that you have an external json file with a number of objects in an array.

 

Task: Create a SAPUI5 application which contains a table and bind a table with json file. Create a button to calculate the total price of the products and show the total price in the message box.

 

Hint: To find sum of all elements, iterate through each element and add the current element to the sum. Which is run a loop from 0 to n. The loop structure should look like for(i=0; i<n; i++).

 

Step 1.

 

In XML view file add Table and Button item controls :

<content>
	<Table items="{productsModel>/products}" id="tableProd" class="sapUiMediumMargin">
		<columns>
			<Column id="ProductId">
				<Text text="Product ID"></Text>
			</Column>
			<Column id="ProductName">
				<Text text="Product name"></Text>
			</Column>
			<Column id="Category">
				<Text text="Category"></Text>
			</Column>
			<Column id="Price">
				<Text text="Price"></Text>
			</Column>
		</columns>
		<items>
			<ColumnListItem>
				<cells>
					<Label text="{productsModel>ProductId}"></Label>
					<Label text="{productsModel>ProductName}"></Label>
					<Label text="{productsModel>Category}"></Label>
					<Label text="{productsModel>Price}"></Label>
				</cells>
			</ColumnListItem>
		</items>
	</Table>
	<Bar>
		<contentMiddle height="100%">
			<Button text="Calculate" icon="sap-icon://simulate" press="onClick" class="sapUiLargeMargin"></Button>
		</contentMiddle>
	</Bar>
</content>

Step 2.

 

Create a JSON model with info for our Table and bind it to the control.

{
	"products": [{
			"ProductId": "1",
			"ProductName": "Name1", 
			"Category": "Category1",
			"Price": "100"},
			{
			"ProductId": "2",
			"ProductName": "Name2", 
			"Category": "Category2",
			"Price": "120"},
			{
			"ProductId": "3",
			"ProductName": "Name3", 
			"Category": "Category3",
			"Price": "140"},
			{
			"ProductId": "4",
//\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\

	

onInit: function () {
			var oModel = new sap.ui.model.json.JSONModel();
			oModel.loadData("./model/products.json");
			this.getView().setModel(oModel, "productsModel");
		},

Step 3.

 

In the standard way we first declare the variable sum and set its initial value of zero. Next, we use a standard for loop to iterate through our array numbers and total up the array using sum.

onClick: function () {

			var sum = 0,
				items = this.getView().byId("tableProd").getItems();

			for (var i = 0; i < items.length; i++) {

				sum = sum + Number(items[i].getBindingContext("productsModel").getObject().Price);

			}

			MessageBox.show("The total price:" + " " + sum);

		}

 

Our mini app will look as follows:

 

Simple, but is probably not the best solution to the task? I’d love to hear from you with better code for our mini Product sum application!

 

Thank you for reading! Hope you liked it:)

 

For your convenience please find below the links to all series:

In exercise #1 we practice to add one or more elements at the beginning and the end of an array.

In exercise # 2 we perform calculations using Number() constructions and Array methods.

In exercise #3 we practice to remove elements from our JSON model and calculated the number of Days between two dates

 

Assigned Tags

      4 Comments
      You must be Logged on to comment or reply to a post.
      Author's profile photo Volker Buzek
      Volker Buzek

      Hi, cool effort, nice to see some "typical" coding tasks explained in greater detail!

      However, I'd suggest to work in some better practices such as:

      utilize MVC more instead of doing "VC" only 🙂

      in 2.1, "Useful Number method",

      first bind your inputs to a View Model à la

      <Input id="input2" type="Number" value="{viewModel>/value2}" />

      then work with the input number via the view model instead of directly accessing the control:

      const item2Value = this.getModel("viewModel").getProperty("/input2")

      that way data binding, interaction lifecycle and data validation can be done the "UI5-way" 🙂

      use JS native power and be more lazy

      in 2.2, Array method,

      save yourself some typing and map-reduce the sum via...well Array.reduce():

      const items = this.getView().byId("tableProd").getItems()
      
      const sum = items.map(item => item.getBindingContext("productsModel").getObject().Price) // get each item's price
        .reduce( (accumulator, currentValue) => accumulator + currentValue, 0) // compute the total sum

      more details at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

      PS: all above code top of my head, so take with a grain of salt 🙂

      have fun!

      Best, V.

       

       

      Author's profile photo Nadya Brown
      Nadya Brown
      Blog Post Author

      oh, so nice! many thanks for your practical/valuable solution, I have now something to look at:)

      Author's profile photo Gaurav Karkara
      Gaurav Karkara

      Thanks Nadya for these crisp blogs!

      Probably you would want to link all your series blogs in each blog? It will be helpful for people to follow.

      Gaurav

      Author's profile photo Nadya Brown
      Nadya Brown
      Blog Post Author

      Many thanks Gaurav for you kind notes and of course I should add the links. Pleased to meet you and have a great weekend:)