Hey! Welcome to week 2 of the tutorial series “SAPUI5 – from Zero to Hero”. Now, that our configuration is complete, we will start with a little bit of programming. At the end of this tutorial, you will be able to:

  • Read, understand and make use of the SAPUI5 Software Development Kit
  • Understand views & controllers – the V and the C of the MVC pattern
  • Embed SAPUI5 elements into your project
  • Understand different layout options
  • Understand the concept of i18n and make use of it

If you have missed last week’s tutorial, you can access it here – SAPUI5 – The What and the How

Ready to roll? Then grab a cup of tea or coffee and read on :)

Also, don’t forget to subscribe to stay up to date!

The SAPUI5 Software Development Kit

As briefly mentioned last week, there is a collection of important “must have” links that we need, to be able to develop using SAPUI5. Trust me, even the most experienced developers look at the SDK. It would simply be pointless to memorise all of the elements and their events, properties, methods, etc. Additionally, the library often changes – new properties are introduced, old ones are deprecated, etc. Hence, there’s no other way around it :)

API Reference – https://sapui5.hana.ondemand.com/#/api

Let’s take a look at a sample element and go through the details we can find in the documentation.

As an example, we will take the Button element from the sap.m library – link

Navigation around the page is quite self-explanatory. SAPUI5 guys have done a good job with making the SDK usable. We will not go through everything you see on the screen for this element. Instead, we will focus on the most important, not to overwhelm you at the start.

So, starting from the top and going LTR:

  • class sap.m.Button tells us that this Button element is part of the sap.m namespace. We need to take this into account as this will need to be imported into our project to use this element. You’ll see it later
  • Control Sample – The beauty of this SDK is that you get a couple of sample implementations for each element. At the beginning of the SAPUI5 journey, it’s a good idea to just go into the sample, copy the code into your project and customise it to your requirements. We’ll get to the samples later but here is one of the ways of finding them
  • UX Guidelines – Remember that SAPUI5 and Fiori were developed to deliver unified experience. We wouldn’t be able to do that without User Experience guidelines! If you ever find yourself wondering how an element should be used, here is where you’ll find out more
  • Extends – The class this element extends, we can use the methods & properties of the extended class
  • Now, the tabs:
    • Overview – general information about the element and its behaviour
    • Constructor – its JavaScript constructor, if you decide to implement it in the controller and not the view
    • Properties – in simple terms – the settings that can be applied to the element
    • Aggregations – Information about the children that can be embedded inside the given element
    • Associations – properties which store the ID of another element in order to connect to it in an abstract way. Example: Label and a text field. In theory – 2 different elements. However, often used together. To be able to connect them with each other, we use an association – ‘The label is a “LabelFor” the Text Field’
    • Events – list of behaviours that the selected element handles. Example for a button would be the press event. It would allow us to define a function to be triggered when the button is pressed (a button without any action on press would be pointless, right?)
    • Methods – list of methods that can be called on the selected element. Example would be the “firePress” method to programmatically trigger the press event to reuse the functionality of the attached callback function.

That’s pretty much it on a high level. As we work through the training course, we will visit the SDK a lot. So, if you don’t like it now – take another sip of tea/coffee and try to make friends with it once again. It ain’t that bad!

VC (not Venture Capital)

MVC is an acronym you have definitely come across if you have any frontend programming experience. It stands for Model, View, Controller and it is a pattern of separating the app logic in these 3 categories. We will not go into details on MVC here as it’s a well-known programming concept already described by thousands of articles on the internet so… have a google :)

This week, we will leave the ‘M’ of MVC aside. The reason for this is that it is often misunderstood and misused by beginners and I would like to dedicate one complete week to it, along with the concept of Binding. Instead, we will go through the View and the Controller.

View

Theoretically, all of the elements you see in front of you should come from some sort of a view in the app. I say theoretically because as already mentioned, it is possible that some elements are instantiated and embedded using controllers, but for now, let’s focus on the view.

As already mentioned in week 1, SAPUI5 caters for 4 types of views: JSON, JavaScript, XML and HTML. I personally only use XML and this is the one we will cover in this course.

Let’s now open the project we have created last week and open the default view which you’ll find in webapp/view folder.

Our default view follows the usual XML-like tree structure. Which means that we need a common parent of all of the elements. In the case of SAPUI5, the parent is always mvc:View. You are now probably wondering about the ‘mvc:’ in front of the View but don’t wonder too much! mvc: is a namespace that is declared somewhere in this document and if you look closely, one of the attributes of this element is xmlns:mvc=”… which basically tells the compiler “Hey! Take the library I’ve specified in this attribute and assign it the ‘mvc’ namespace everywhere in this file”. Note that ‘mvc’ here is for clarity but in fact, it can be anything! To believe it, try changing it and run the app, you will see that it still works as it should (make sure you change it in all of the relevant places):

The use of namespaces is to separate code and ensure there’s no overlap of element names. For example, if you decide to use a custom library called com.customlib and this library contains an element called Label. However, later on in your code, you want to use the standard Label element contained in the sap.m library. How would the compiler know which is which? Well this is exactly where you’d use namespaces. Your View initialisation line would then contain the following 2 attributes:

  • xmlns:m=”sap.m”
  • xmlns:cust=”com.customlib” (note – cust can be replaced with anything you wish)

Then, in the code, you would separate them by using the appropriate namespace tag:

  • m:Label
  • cust:Label

Easy, right? That’s it for namespaces! It’s a simple concept but you need to be really careful as any misuse will cause XML parse errors that are often difficult to find.

The next property you see on the screenshot is controllerName, it is already pre-filled on creation and it simply points to the view’s underlying component.

Now, displayBlock came in with a default value of true but what is it and where to find out more about it? SDK! Let’s find the View element in the SDK and see what the displayBlock property does. Here it is, we will leave it with the default value

The last property to consider in this view element is xmlns. This one simply sets the default library to use, when no namespace is given. The best practice is to always default it to ‘sap.m’, as is the case here.

The underlying child elements are all part of the default library, take a look at the SDK to see what they do!

Controller

You saw the view, now is the time to take a look at the default controller and see what’s inside it, you will find it in the webapp/controller folder:

There isn’t much in it, really. First, we have the controller definition (line 1), then – we import the necessary library (line 2). In the function importing parameters we give the imported libraries a reference variable (in this case, sap/ui/core/mvc/Controller can be simply references as ‘Controller’ in the body of the controller). Finally, our view is referenced on line 6 and starting from line 7 we can insert our methods. That’s it from the basics.

There are, however, some things that beginners often mess up, while working with the controllers. One such example is the order of imported libraries and their reference variables. For example, imagine that we need 3 libraries in this controller: sap.ui.core.mvc.Controller, sap.ui.core and sap.ui.layout. It is extremely important that the 3 reference variables (line 3) above are given the same order as the actual import code (line 2). Otherwise, we might have a case where reference variable Core refers to the library sap.ui.layout – a recipe for disaster and ‘element X not found in library Y’ type errors.

Let’s get coding

If you have got so far and you still haven’t fallen asleep, that’s a good sign! In this section, I will try not to bore you too much. Instead, we will do some hands-on work and start enhancing our newly created project.

We will start by adding a layout to our application and embedding 2 elements inside it – a textfield and a button. When the button is pressed, the content of the text field will be printed in an alert box. This way, you will touch some basic functions and concepts behind SAPUI5.

  • Let’s first find the Vertical Layout in the SDK

  • After navigating inside, we can see everything we need to be able to use it
    • library: sap.ui.layout

  • Now, let’s open our SAP WebIDE and import the new library into our xml view by adding the following attribute to view definition xmlns:layout=”sap.ui.layout”
  • Next, we will insert the Vertical Layout tags into our code, the result should be the following

  • As you can see, we can give the layout an optional ID parameter. This will enable us to reference the view from the controller, if such need arises
  • We can also inspect the app by running it and opening the development tools. Our ID can be found in the DOM, even though nothing has changed.

  • Next step is to find the button and the textfield in the SDK. Go on and find sap.m.Button and sap.m.Input
  • As you probably remember, samples is a very useful feature in the SDK where we can find code ready to be copied into our app. You can do that, or try to build it yourself :)
  • The look and the code we are after is:

You can click the button all you want, it won’t do anything until we tell it to, and here is how:

  • First, we need to create a function in our controller which will get triggered once the button is pressed. We will call it ‘onButtonPress’ but it can be anything.

  • To complete our example, we will also need an alert box. This is a standard JavaScript alert function which isn’t often the best option but for the sake of this tutorial, it’ll do. Let’s insert it into the function

You can notice the warning that comes from ESLINT (Syntax checks) which is enabled in SAP WebIDE. As already mentioned, you shouldn’t use it in a productive app but for quick testing, I often like to make use of it. The end result should be, that a standard browser pop-up shows up with the text “Hey! Somebody clicked me…”. But wait! How will the button know that it should call this function?? Once again, it will not until we tell it to :)

  • Back to our view, we should now assign the created callback function to the ‘press’ event of the Button element

This will directly trigger the function we have just created in the controller. Try it!

Coool, we have a bit of action! But the initial idea was to read the input from the text field and display it in the alert box. So far, we have just got the alert, so, let’s keep going:

  • Browse through the SDK for the m.Input element and find the method that’s responsible for getting the value of the Input. The method’s name is getValue. You’d never guess, would you? But what to do with this method?
  • When dealing with methods we mainly implement them in the controller (some inline view implementations are also possible but we’ll not go through them now). So, we first need an object to call this method on. Since we want to get the value of the Input field, we need to assign an ID to it. Make it “inputField”

  • Now comes the fun part, in the callback function of the button press event, we will get reference to the input field and read its value using the found method.

var value = this.getView().byId(“inputField”).getValue();

Explanations:

  • this.getView() – gets reference to the view our controller is attached to. We need it to find the field that resides inside it
  • byId(“inputField”) – essentially says ‘give me the element with ID = inputField’
  • getValue() – the method we found earlier to retrieve the value from the m.Input element

Ok, we’ve got the code to retrieve the value, now lets integrate it into actually displaying the fetched value in the alert box:

Tadam!!

Exercise: Add a label element to the layout and change the behaviour of the button to update the label element with the value from the input field. Once you are done, you can move on.

Layouts

Layouts are elements used to position elements on the screen. SAPUI5 offers various layouts which will help you achieve your desired look. As you do more and more, you will probably have your favourites that you’ll use in most of the usual developments you do. Layout is translated into a div with corresponding styling. Therefore, as you have probably already guessed, it only manages the elements that are its children.

VerticalLayout should already be familiar to you. If you now replace VerticalLayout in your code with HorizontalLayout, you will see the following result

Another common layout to use is the HBox and VBox, they essentially correspond to the flex-direction: ‘horizontal’ (HBox) and ‘vertical’ (VBox) that you have probably already seen if you’ve developed using CSS. If not, take a look at this end to end guide to FlexBox.

As an example, we will now change our HorizontalLayout to HBox. Note that I removed the layout namespace as HBox belongs to the sap.m library.

The result is exactly like the one we saw in the case of HorizontalLayout because we haven’t used any of the magical properties HBox has to offer. For example, the ‘justifyContent‘ property. It can help us position elements across the main axis (Horizontal for HBox, Vertical for VBox) with the following options:

I won’t go through them all, spend some time with it yourself and see how they work. Instead, I’ll show you how to achieve something everybody hates – positioning elements in the center of the screen. To do that, we will use the following 3 properties:

  1. justifyContent – to position the child elements across the main axis (Horizontally)
  2. alignItems – to position the child elements across the secondary axis (Vertical)
  3. height – to set the height of the element (otherwise it has no way of knowing where the vertical center is)

So, change the HBox definition to

and the result is as expected :)

Another interesting layout that you should look into is the grid layout. Try to figure it out and let me know in the comments if you encounter any issues.

These are just a few from the wide range of layouts offered by SAPUI5. As you get more and more familiar using the SDK, you will be able to use them effectively. I will try to use different layouts throughout this course so you get an idea on how to work with them.

I18n

When developing apps, we always consider the end users. As you are probably aware (if not, then I’m not sure if SAPUI5 should be your biggest priority!), there are many different languages in the world. How do we build apps that can be easily translated into different languages? The answer lies in the concept commonly known as i18n which is an acronym for “Internationalisation“. There are exactly 18 letters between the i and the n of this word, hence the name.

The concept is based on data binding which we will discuss later on in the course but I decided to include it now as it’s relatively simple and we should not postpone it for long.

If you’ve followed along with the course so far, I’m pretty sure that at some point you were annoyed about the fact that the title of our app still says “Title”. “WHY HASNT HE CHANGED IT??!?!”. If you are perceptive enough, you have probably also noticed the Page element with the Title property being assigned some strangely-looking string:

title=”{i18n>title}”

What you see as the value of the title property is called binding and in this case, more specifically – property binding. We bind the property title to the i18n model’s key ‘title’. “Huh?? What are you talking about?”. Have a look:

If you open webapp/i18n/i18n.properties, you will see some texts within it

If you look closely, what you see assigned to the title key is what we actually see on our screen. Now, try changing it to whatever you want and refresh our app

Now, let’s go back to the example we were working on and modify it to display “X is beautiful” where X is the dynamic value from the input field but “is beautiful” is a fixed string that comes from i18n.

First, we will add a new string in the i18n.properties file:

The {0} is a placeholder you use to insert a parameter into the text. It is crucial to cater for various word order rules that languages might follow. If you had only created ‘is beautiful’ as the translatable and decided to programmatically concatenate the value in the controller, you could end up with issues for languages where this sentence would be expressed in the order adjective + verb + subject (I don’t know if languages that follow this example exist but trust me, it’s correct like this! I just can’t think of anything right now!) .

You’ve seen an example of i18n in the view, but how to do it in the controller? First, you need to get reference to the ResourceBundle of the component’s i18n model. It might sound confusing for now but don’t think about it too much, we will go through it in more detail later on. For now, just declare i18n as such:

var i18n = this.getOwnerComponent().getModel(“i18n”).getResourceBundle();

Now, to retrieve a string from the i18n file, we call the getText method on the i18n variable passing in the string name “isBeautiful” and the required parameter. The end result is

which in the app leads to the following result

Btw: This layout looks ugly, let’s quickly change it to VBox

Not much better, but at least it doesn’t hurt my eyes so much anymore…

Alright, why are we doing it? Well, if we efficiently use the i18n concept, translation of the entire app is just a matter of sending the i18n file to the translator and when finished – uploading it into the app. To see how it works, let’s change this text to German

Go to Run > Run Configurations > Run index.html > URL Components on the toolbar and fill it in with the following parameter and value

Press Save and Run and try out our logic

I hope you weren’t expecting any tangible results at this stage. We still haven’t added the translation files :)

In the project explorer, create a new file called i18n_de.properties and place it in the webapp/i18n folder. Once created, add just 1 line of text:

Now, go back to our app, save and re-run with the parameter. You should now see the translated text :)

Summary

That’s it! This week we’ve briefly touched on SAPUI5 elements and how to use them in our app. I’ve given you an introduction to layouts and how to use them and finally, you’ve touched a bit of the i18n concept.

If you feel like practicing more, try changing the remaining texts in our app to use i18n, after that, try introducing another language, for example French. Once you have 2-3 languages, add buttons to navigate between them by changing the URI parameter sap-ui-language. Let me know in the comments if you encounter any difficulties!

Topic for next week: Why bind?