How to add Unit Annotations in SAP UI5 Table

The unit of measure for a quantity can be displayed using the Unit Annotations. The Unit annotations in the metadata are represented as below.

                        <EntityType Name="CustomerType"
                            sap:label="Customers"
                            sap:content-version="1">
                            <Key>
                                <PropertyRef Name="Id" />
                            </Key>

                            <Property Name="Id"
                                Type="Edm.String"
                                Nullable="false"
                                MaxLength="10"
                                sap:visible="true"
                                sap:label="Customer ID"
                                sap:creatable="false"
                                sap:text="Name" />
                            <Property Name="FC"
                                Type="Edm.Byte"
                                sap:label="Field control" />
                            <Property Name="Name"
                                Type="Edm.String"
                                MaxLength="70"
                                sap:field-control="FC"
                                sap:creatable="false"
                                sap:updatable="true"
                                sap:label="Customer Name" />
                            <Property Name="Weight"
                                    Type="Edm.Double"
                                    sap:label="Weight"
                                    sap:unit="Unit" />
                            <Property Name="Unit"
                                  Type="Edm.String"
                                  MaxLength="512"
                                  sap:semantics="unit-of-measure" />
                        </EntityType>

The http Response will look like below

            {"d": {
                            "__count": "3",
                            "results": [
                                {
                                    "__metadata": {
                                        "id": "Customer_Odata_Service.CustomerSet/CustomerSet('1000')",
                                        "uri": "Customer_Odata_Service.CustomerSet/CustomerSet('1000')",
                                        "type": "CustomerNamespace.CustomerType"
                                    },
                                    "Id": "1000",
                                    "Name": "Mani",
                                    "FC": 1,
                                    "Weight": "70",
                                    "Unit": "Kg"
                                },
                                {
                                    "__metadata": {
                                        "id": "Customer_Odata_Service.CustomerSet/CustomerSet('1001')",
                                        "uri": "Customer_Odata_Service.CustomerSet/CustomerSet('1001')",
                                        "type": "CustomerNamespace.CustomerType"
                                    },
                                    "Id": "1001",
                                    "Name": "Raju",
                                    "FC": 1,
                                    "Weight": "70",
                                    "Unit": "Kg"                                    
                                },
                                {
                                    "__metadata": {
                                        "id": "Customer_Odata_Service.CustomerSet/CustomerSet('1002')",
                                        "uri": "Customer_Odata_Service.CustomerSet/CustomerSet('1002')",
                                        "type": "CustomerNamespace.CustomerType"
                                    },
                                    "Id": "1002",
                                    "Name": "Jack",
                                    "FC": 3,
                                    "Weight": "70",
                                    "Unit": "Kg"                                    
                                }                                 
                            ]
                }
            }

With the Metadata unit annotations and the corresponding http response will result in rendering a SAP UI5 Smart Table with values (Weight along with the unit) like below

Unit Annotations in SAP UI5 Table

HTTP vs HTTPS

Both HTTP and HTTPS are protocols for communicating over the internet. If you have a website or probably used a website might have come across these things namely http:// or https://

What is HTTP ?

Hyper Text Trasfer Protocol is a set of rules defining how information is transfered over internet. It is a stateless protocol built on top of TCP protocol in application layer. User connects to your site are through a insecure connection vulnerable to security attacks. Here plain text is transmitted as it is without encryption.

What is HTTPS?

Hyper Text Transfer Protocol Secure is a advanced and secured version of HTTP. Here everything is encrypted with SSL/TLS protocol. Protects sensitive data from being stolen. It requires SSL certificate.

HTTP vs HTTPS

How to use CSS class?

A CSS class is an attribute used to define a group of HTML elements a unique styling and formatting. Class is a group of elements that are similar or unique. For example, when we want to add blue text to a set of paragraphs, or bold red text to set of headings in our website we use CSS class.

How to add a class to your HTML element?

<div class=”class1”>

<p class=”class1”>This is a paragraph</p>

Each HTML element can have multiple classes.

<div class=”class2”>

How to use a class in CSS?

.class1{

width: 50px;

height: 50px;

background: blue;

}

Example:

OUTPUT:

Where can you add CSS classes in HTML?

CSS classes can be added to any HTML elements. Some of the most common ones are:

  • <p> paragraph
  • <body>
  • <h1>, <h2>, …<h6> headings
  • <title>
  • <blockquote>
  • <span>
  • <div>
  • <img> images
  • <button>
  • <a>
  • <links>
  • <embed>
  • <table>

and much more.

How to use CSS selectors

To apply CSS to an element we need to select it. It is used to select the content you want to style

What is CSS selectors?

          CSS selectors define the elements to which a specific set of rules apply. It is the first part of CSS rule. It is a pattern of elements and other terms that tell the browser which HTML elements should be selected to have the CSS property values inside the rule applied to them. The element or elements which are selected by the selector are referred to as the subject of the selector.

Syntax:

Selector{

          propertyName: value;

          propertyName: value;

          }

Types of Selectors:

  • Element
  • ID
  • Universal
  • Class
  • Attribute

Element Selector:

This selects HTML elements based on the element tag name like <p>, <h1> etc.,

p {
  text-align: center;
  color: red;
}

Universal selector

Selects all elements. Optionally, it may be restricted to a specific namespace or to all namespaces.
Syntax: * ns|* *|*
Example: * will match all the elements of the document.

* {
  text-align: center;
  color: blue;
}

Type selector

Selects all elements that have the given node name.
Syntax: elementname
Example: input will match any <input> element.

Class selector

Selects all elements that have the given class attribute.
Syntax: .classname
Example: .index will match any element that has a class of “index”.

.index {
  text-align: center;
  color: red;
}

To specify only specific HTML elements of a class to be affected

p.index {
  text-align: center;
  color: red;
}

Here only elements with tag <p> are affected in class index.

ID selector

Selects an element based on the value of its id attribute. There should be only one element with a given ID in a document.
Syntax: #idname
Example: #p1 will match the element that has the ID “p1”.

#p1 {
  text-align: center;
  color: red;
}

Attribute selector

Selects all elements that have the given attribute.
Syntax: [attr] [attr=value] [attr~=value] [attr|=value] [attr^=value] [attr$=value] [attr*=value]
Example: [autoplay] will match all elements that have the autoplay attribute set (to any value).

a[target] {
  background-color: yellow;
}

CSS Grouping Selector

Grouping Selector selects all HTML elements with same style definitions.

To group selectors , we separate with comma ,

h1, h2, p {
  text-align: center;
  color: red;
}

How to select the default columns for Smart table in SAP UI5

‘initiallyVisibleFields’ property of the SAP UI5 Smart table is used to select the default columns for the smart table.

initiallyVisibleFields=”Id,Name”

As you see above, the fields(columns) of the smart table are separated by Comma. The columns will be visible in the same order as mentioned above with customer Id as first column and Customer Name as second column.

Important points to keep in mind while using this Property

  • The ‘initiallyVisibleFields’ Property must be used only if the CDS view is created without the Line Item Annotations. So there should not be any Line Item Annotations in the metadata generated.
  • Only during the initialization, the ‘initiallyVisibleFields’ Property of Smart Table can be used. It cannot be modified after the Smart table control is initialized.
  • The Property is not Validated. So if the fields are not mentioned properly, then it will not work. Like if spaces exists additionally or if there is any special symbols, then the columns will not be displayed properly.

            <core:View xmlns:core="sap.ui.core" controllerName="initialView.controller"
                xmlns="sap.m"
                xmlns:smart="sap.ui.comp.smarttable"
                xmlns:customData="http://schemas.sap.com/sapui5/extension/sap.ui.core.CustomData/1"
                height="100%">
                <Page id="page1" title="Customers1">
                   <VBox fitContainer="true">
                       <smart:SmartTable id="smartTable1" entitySet="CustomerSet"
                           tableType="ResponsiveTable"
                           showFullScreenButton="true" header="Customers" showRowCount="true"
                           editTogglable="true"
                           customData:useSmartField="true"
                           useTablePersonalisation="true"
                           initiallyVisibleFields="Id,Name"
                           enableAutoBinding="true">
                       </smart:SmartTable>
                   </VBox>
                </Page>
            </core:View>

The priority in which the columns are displayed in the following

  1. Initially if the XML View contains some fields, then these fields are displayed first. This takes the highest priority.
  2. If the LineItem Annotations are present in the metadata, then these fields are displayed second.
  3. Atlast, the initiallyVisibleFields are taken in to consideration. It appears at the end in the display.

Understanding Document Object Model (DOM)

Document Object Model (DOM) is an Application Programming Interface (API) for manipulating HTML documents. When a webpage is loaded, the browser creates a DOM of the page. It defines a logical structure of documents and the way a document is accessed and manipulated. Using JavaScript in a HTML webpage is to make our page more interactive and dynamic. The DOM provides the mechanism for JavaScript to achieve this. It is an interface that allows a programming language to manipulate the content, structure, and style of a website.

               DOM represents an HTML document as a tree of nodes. DOM is cross-platform and language independent way of manipulating HTML and XML documents.

HTML DOM model is created as a tree of Objects. With the Object model, JavaScript gets all power it needs to make dynamic HTML.

  • JavaScript can change all HTML elements in a page.
  • JavaScript can change all HTML attributes in the page.
  • JavaScript can change all the CSS styles in the page.
  • JavaScript can remove existing HTML elements and attributes.
  • JavaScript can add new HTML elements and attributes.
  • JavaScript can react to all existing HTML events in the page.
  • JavaScript can create new HTML events in the page.
<html>
<head>
<title> DOM Example </title>
</head>
<body>
<p>DOM Tree</p>
<p id =’text’> This is a DOM tree </p>
</body>
</html>

The DOM represents a document as a hierarchical tree of nodes which have root node and child nodes. One characteristic of DOM is how it handles attributes. Attributes are property of the element node and are made up of name and value pair. Also, there are several node types in the tree each representing different information or markup in HTML document.

Four main nodes:

Document node:

It is the root node added at the top of tree and represents entire page in the browser. It is the starting point in DOM tree, and you need to navigate via this node to access any other node in DOM tree.

Element node:

All HTML elements like heading tags <h1>…<h6> , paragraph tags <p> are element nodes. You need to navigate via these nodes to gain access to its attributes and text.

Attribute node:

The opening tag in an HTML document contains attributes. These are not children of element node but part of them.

Text node:

Text content within the element are stored here. These nodes cannot have further child nodes.

JavaScript-HTML DOM Methods

  • HTML DOM methods are actions you can perform on HTML elements
  • HTML DOM properties are values of HTML elements that you can set or change.

How to access HTML elements in a HTML page.

  • Finding HTML elements by id

Get one of HTML object which have an id attribute.

document.getElementsById( );

  • Finding HTML elements by tag name

Get one or more of a HTML tag.

document.getElementsbyTagName( );

  • Finding HTML elements by class name

Get one or more of HTML object which have a class attribute.

document.getElementsbyTagName( );

  • Finding HTML elements by CSS selectors

Get the first of HTML object which is a CSS selector element.

document.querySelector( );

  • Finding HTML elements by querySelectorAll

Get the one or more of HTML object which is a CSS selector

document.querySelectorAll( );

Changing HTML Content

The innerHTML is a property of Element which is useful for getting or replacing the content of HTML elements.

Reading the innerHTML property of element

let content = element.innerHTML;

Setting the innerHTML property of element

Element.innerHTML = newHTML;

Do not use innerHTML to set a new content that you have no control over to avoid a security risk.

DOM Manipulation

Another technique to add/remove HTML content is DOM Manipulation.

Create a HTML element

document.createElement(element)    

Remove a HTML element

document.removeChild(element)

Add a HTML element

document.appendChild(element)

Replace a HTML element

document.replaceChild(new,old)

Write into the HTML output stream

document.write(text)

Conclusion:

Hence so far, we have discussed the various aspects of Document Object Model (DOM)

Understanding CSS Grid and Flexbox Layout.

Flexbox and Grid:

Cascading Style Sheet is a style sheet language used to describe how a HTML document is displayed. CSS is a foundation technology of world wide web, along with HTML and Javascript. To simplify the creation and maintenance of webpages responsive layouts are developed in CSS. Now let us see about the Grid and Flexbox layouts in CSS.

What is CSS Flexbox?

          CSS Flexbox is a one-dimensional layout model that makes it easy and flexible in designing effective layouts. This model helps in allocating and aligning space among items. Flex items are positioned inside a flex container along a flex line. By default there is only one flex line per container.

Basic concepts of Flexbox:

Two axes of Flexbox:

main axis: The main axis is the primary axis along which the flex items are aligned. It is defined by flex-direction, which has 4 values:

  • row
  • row-reverse
  • column
  • column-reverse

In row or row-reverse our main axis will run along the row in the inline direction.

In column or column-reverse our main-axis will run from top of the page to bottom along the block direction.

Cross-axis:

The cross-axis runs perpendicular to the main axis, therefore if our flex-direction is set to row or row-reverse the cross-axis runs down the column.

If flex-direction is set to column or column-reverse, the cross-axis runs across the row.

main-start and main-end:

          The flex items are placed in the container with items beginning with main-start and ending with main-end.

CSS Flexbox Properties:

PropertyDescription
flex-directionDefines in which direction a container wants to stack the flex items.
flex-wrapSpecifies whether flex items should wrap or not.
flex-flowShorthand for setting both flex-direction and flex-wrap
justify-contentUsed to align the flex items with values center, start, end, space-around, space-between.
align-itemsVertically align the flex items along the cross axis.
align-selfUsed on flex items. It overrides the container’s align-items property.

Example of flexbox:

OUTPUT:

What is Grid Layout?

          CSS Grid Layout is a 2D grid-based layout with rows and columns, useful in creating more complex and organized layouts without using floats and positioning. To define a Grid container, you will have to pass a display:grid property to your element

Important terms:

  • row
  • column
  • cell
  • grid line
  • gutter

Grid Container:

          A grid container is an element on which the display: property is applied. It is the direct parent of all the grid items. The items of the grid are placed inside rows and columns.

OUTPUT:

CSS Grid Properties:

PropertyDescription
column-gapSpecifies the gap between the columns
gapA shorthand property for the row-gap and the column-gap properties
gridA shorthand property for the grid-template-rows, grid-template-columns, grid-template-areas, grid-auto-rows, grid-auto-columns, and the grid-auto-flow properties
Grid-areaEither specifies a name for the grid item, or this property is a shorthand property for the grid-row-startgrid-column-startgrid-row-end, and grid-column-end properties
Grid-auto-columnsSpecifies a default column size
Grid-auto-flowSpecifies how auto-placed items are inserted in the grid
grid-auto-rowsSpecifies a default row size
grid-columnA shorthand property for the grid-column-start and the grid-column-end properties
grid-column-endSpecifies where to end the grid item
grid-column-gapSpecifies the size of the gap between columns
grid-column-startSpecifies where to start the grid item
grid-gapA shorthand property for the grid-row-gap and grid-column-gap properties
grid-rowA shorthand property for the grid-row-start and the grid-row-end properties
grid-row-endSpecifies where to end the grid item
grid-row-gapSpecifies the size of the gap between rows
grid-row-startSpecifies where to start the grid item
grid-templateA shorthand property for the grid-template-rowsgrid-template-columns and grid-areas properties
grid-template-areasSpecifies how to display columns and rows, using named grid items
grid-template-columnsSpecifies the size of the columns, and how many columns in a grid layout
grid-template-rowsSpecifies the size of the rows in a grid layout
row-gapSpecifies the gap between the grid rows

Substring() vs Slice() in JavaScript

What is substring()?

substring() method returns part of the string from start index upto end index but excluding the endindex. It extracts characters between two indices from a string and return the substring. It does not change the original string.

Syntax:
substring(indexStart)
substring(indexStart, indexEnd)

Parameters:

indexStart – Index of first character to include in substring.

indexEnd – It is optional. It denotes the first character to exclude from the returned string.

When indexEnd is not there, the substring() method returns characters upto the end of the string.

Return value – A new sub string containing part of original string.

What will happen if both index start and end are same?

const str = ‘Abaython’
str.substring(3,3)

When both start and end index are same will return an empty string.

If start index greater than end index?

const str = ‘Abaython’
str.substring(4,2)
Output:

ay

Here it will simply swap the parameters as,

str.substring(2,4)

So, the output is ay.

If indexEnd is omitted?

const str = ‘Abaython’
str.substring(4)
Output:

thon

Here it will return upto the end of the string starting from index 4

Substring() vs slice()

Though in both methods the parameters are same, the main difference is using negative values.

In substring() method negative values are considered as zero.

const s = 'Abaython';
console.log(s.substring(-4,5))
Output:

Abayt

Here -4 is considered as 0 and returns from the start of the string.

Keypoints to note:

Similarities:

  • In both methods the parameters are same. If start and end index are equal both returns an empty string.
  • If end index is omitted then the characters are extracted upto the end of the string.
  • Any parameter greater than string length then string length is used instead.
  • NaN treated as 0.

Differences:

  • In case of startindex > endindex,

Substring() method swaps the parameters.

Slice() method returns empty string

  • If any argument has negative values,

Substring() method treats them as 0

Slice() method counts from the end of the string for negative values

Difference between substr and substring

What is substr() method?

Substr() method returns a particular number of characters starting from specified index.

Syntax:
substr(startIndex, Length)
substr(startIndex)

startIndex – index of first character to include in the return string

length – It is optional determines the number of characters to extract.

Return value – A new string containing the specified part of given string.

Example:
let str = "Abaython";
console.log(str.substr(1,2));
console.log(str.substr(-2,2));
console.log(str.substr(1));
console.log(str.substr(-1,2));
Output:

ba

on

baython

n

Points to note:
  • start >= str.length, an empty string is returned.
  • If start < 0, the index starts counting from the end of the string. More formally, in this case the substring starts at max(start + str.length, 0).
  • If start is omitted or undefined, it’s treated as 0.
  • If length is omitted or undefined, or if start + length >= str.length, substr() extracts characters to the end of the string.
  • If length < 0, an empty string is returned.
  • For both start and length, NaN is treated as 0.

Though substr() is not strictly a deprecated function, it is considered a legacy function and you should avoid using it as possible as you can. It is not part of JavaScript and may be removed in the future. So, you can use the substring() method instead.

Difference

The main difference lies in the parameter the second parameter in substr() method indicates the number of characters to extract whereas in substring() the second parameter denotes the index upto which we need to extract excluding the particular index.

For negative values in parameters in substr() for first argument index counted from back and second argument is considered as zero. In substring() simply considered zero.

How to split a string into an array of substrings?

JavaScript has many string methods. Today we will explore split() method. As the name suggests it splits a string.

A string is a sequence of characters in a programming language.

Eg: “Abaython”, “JavaScript”.

We can create a string using

  • String literal:

const info = “Hello Abaython!”

  • Using string() constructor:

const info = new String(“Hello Abaython!”);

split() method:

String method used to split a string into an array of substrings using a delimiter. It returns a new array of substrings. It does not change the original string.

Syntax:

               string.split([separator, [,limit]]);

The parameters : separator and limit are optional.

Separator: determines where each split should occur in original string. It can be a string or a regular expression. If you omit this, split() will return the entire string. If (“ “) is used as a separator, the string is split between words.

Limit:

Zero or positive integer to determine the number of substrings. Split() method will stop when number of substrings equals the limit. If limit is zero, returns an empty array. If it is 1, returns an array with the string.

Return value:

               Returns an array of strings, split at each point where separator occurs in given string.

Lets explore some examples:

Without separator:

// without separator

const str = ‘Hello Abaython’;

str.split();

Output:

[‘Hello Abaython’]

How to split a string into individual characters?

We need to use separator here

const str = 'Hello Abaython';

str.split(''); // without space
Output:

 [‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘A’, ‘b’, ‘a’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’]

Note that spaces are also considered as characters here.

How to split a string into individual words?

We need to use separator with space.

const str = 'Hello Abaython';
str.split(' '); // with space
Output:

[‘Hello’, ‘Abaython’]

Using limit parameter:

How to return the first word of the given string?

You just need to add the limit as 1 to return first word.

const str = 'Hello Abaython';
str.split(' ',1);
Output:

[‘Hello’]

What will happen if I change the limit to 0?

Lets see,

const str = 'Hello Abaython';
str.split(' ',0);
Output:

[]

It will return an empty array.

How to split the sentences in a paragraph?

let para = 'Hello! JavaScript? Abaython. Abap.';
let sent = para.split(/[!,?,.]/);
console.log(sent);
Output:

[ ‘Hello’, ‘ JavaScript’, ‘ Abaython’, ‘ Abap’, ” ]

As you can see the !,?,. are not included in output. If you want to include them the regular expression should contain parantheses ( ).