Quantcast
Channel: SAPUI5 Developer Center
Viewing all 789 articles
Browse latest View live

Badge Control

$
0
0

Badge is commonly used these days. So I am sharing an implementation of badge control.

 

CSS

.sap-dennisseah-badge {  margin: 2px;  display: flex;  border-radius: 6px;  font-size: 12px;  height: 30px;  opacity:0.8;  justify-content: flex-start;  cursor:pointer
}

.sap-dennisseah-badge:hover {
  opacity:1;
}

.sap-dennisseah-badge-text{
  margin: 3px;  background-color: transparent;  white-space: nowrap;   display: block;  padding: 5px;  color: #fff;  text-overflow: ellipsis;  overflow: hidden;  font-weight: 550;
}

.sap-dennisseah-badge-num {
  margin-top: 6px;  margin-right: 10px;  padding-top:2px;  background-color: #FFF;  width: 40px;  text-align:center;  border-radius: 5px;  height: 15px;  font-weight: bold;  color: #333;
}

Javascript

  sap.ui.core.Control.extend('sap.dennisseah.Badge', {    metadata: {      properties: {        text: {type:'string', defaultValue: 'untitled'},        value: {type:'int', defaultValue: 0},        width: {type: 'sap.ui.core.CSSSize', defaultValue: '150px'},        color: {type: 'sap.ui.core.CSSColor', defaultValue: '#007cc0'}      },      events: {        pressed: {}      }    },        _width : function(minus) {      var w = parseInt(this.getWidth().replace('px', '')) + minus;      return w + 'px';    },        _style : function() {      var styles = [         'background-color: ' + this.getColor(),         'width: ' + this.getWidth()        ];      return styles.join(';');    },        renderer: function(oRm, oControl) {      oRm.write("<div");      oRm.writeControlData(oControl);      oRm.addClass("sap-dennisseah-badge");      oRm.writeClasses();      oRm.write(' style="' + oControl._style() + '">');      oRm.write('<div class="sap-dennisseah-badge-text" style="width:' +          oControl._width(-40) + '">' + oControl.getText() + '</div>');      oRm.write('<div class="sap-dennisseah-badge-num">' + oControl.getValue() + '</div>');      oRm.write("</div>");    },        onAfterRendering: function() {      var that = this;      this.$().click(function(e) {        that.firePressed({text: that.getText(), value: that.getValue()});      })    }  });

 

And here is how they can be created

  var b1 = new sap.dennisseah.Badge({    text: 'Inbox', value:100, color: 'orange',    pressed: function(e) {      alert('inbox pressed');    }});  b1.placeAt('content');

 

Here is an working example.

 

 

-D


Circular Icons Group

$
0
0

In this blog, we show how to arrange sap.ui.core.Icon in a circle like a circular dialer.

 

CSS

.sap-dennisseah-circular-icons-group {  border: solid;  opacity: 0.9;  border-radius: 50%;
}

.sap-dennisseah-circular-icons-group-btn { 
  position: absolute;  display: table-cell;  opacity: 0.5;  padding: 5px;  border-radius: 100%;
}

.sap-dennisseah-circular-icons-group-btn:hover { 
  opacity: 1;
}

 

Javascript

  sap.ui.core.Control.extend('sap.dennisseah.CircularIconsGroup', {    metadata: {      properties: {        borderwidth: {type: "sap.ui.core.CSSSize", defaultValue: '50px'},        diameter: {type: "sap.ui.core.CSSSize", defaultValue: '100px'},        color: {type: "sap.ui.core.CSSColor", defaultValue: '#007cc0'},        btncolor: {type: "sap.ui.core.CSSColor", defaultValue: '#005990'}      },      aggregations: {        icons: {type: "sap.ui.core.Icon"}      }    },    _style: function() {      var styles = [        'height: ' + this.getDiameter(),        'width: ' + this.getDiameter(),        'border-color: ' + this.getColor(),        'border-width: ' + this.getBorderwidth()      ];      return styles.join('; ');    },            renderer: function(oRm, oControl) {      oRm.write("<div");      oRm.writeControlData(oControl);      oRm.addClass("sap-dennisseah-circular-icons-group");      oRm.writeClasses();      oRm.write(' style="' + oControl._style() + '">');      var icons = oControl.getAggregation('icons');      for (var i = 0; i < icons.length; i++) {        var icon = icons[i];        icon.addStyleClass('sap-dennisseah-circular-icons-group-btn');        oRm.renderControl(icon);      }      oRm.write("</div>");    },        onAfterRendering: function() {      var that = this;      function center() {        var element = that.$()[0];        var d = element.getBoundingClientRect();        return { cx: d.left + d.width/2, cy: d.top + d.height/2 };      }            var icons = this.getAggregation('icons');      if (icons.length === 0) {        return;      }      var angle = 0;      var borderwidth = parseInt(this.getBorderwidth().replace('px',''));      var width = parseInt(this.getDiameter().replace('px',''));      var center = center();      var step = (2*Math.PI) / icons.length;            for (var i = 0; i < icons.length; i++) {        var ic = icons[i];        var ic_obj = $('#' + ic.getId());        var iradius = Math.max(ic_obj.width(), ic_obj.height());        var base = ((width + borderwidth)/2);        var offset = (iradius/2) + 5; // 5 = padding        var x = Math.round(base * Math.cos(angle)) + center.cx - offset;        var y = Math.round(base * Math.sin(angle)) + center.cy - offset;        ic_obj.css('background-color', this.getBtncolor());        ic_obj.css('width', iradius + 'px');        ic_obj.css('height', iradius + 'px');        ic_obj.css('left', x + 'px');        ic_obj.css('top', y + 'px');        angle += step;      }    }  });

 

Example

The control can be created in this manner where you have a bunch of icon and their actions (when being pressed.

  var ctrl = new sap.dennisseah.CircularIconsGroup({    icons: [      new sap.ui.core.Icon({        src: 'sap-icon://globe',        size: '25px',        press: function() {          alert('global');        }      }),      new sap.ui.core.Icon({        src: 'sap-icon://business-objects-explorer',        size: '25px',        press: function() {          alert('explorer');        }      }),      new sap.ui.core.Icon({        src: 'sap-icon://log',        size: '25px',        press: function() {          alert('log');        }      }),      new sap.ui.core.Icon({        src: 'sap-icon://world',        size: '25px',        press: function() {          alert('world');        }      }),      new sap.ui.core.Icon({        src: 'sap-icon://settings',        size: '25px',        press: function() {          alert('settings');        }      })    ]  });

 

Here is an example. and here is how it looks like

 

screenshot.png

 

 

-D

Extending sap.ui.core.Icon

$
0
0

screenshot.png

CSS and Javascript are in github. Once again, this illustrates the power of OpenUI5 where we are created control with a few lines of code.

 

Here is an example of how they are created.

 

jQuery(function() {  jQuery.sap.registerModulePath('sap.dennisseah', 'https://rawgithub.com/dennisseah/openui5/master/controls/sap/dennisseah');  jQuery.sap.require('sap.dennisseah.IconNumIndicator');   var ctrl = new sap.m.HBox({    width: '500px',    items: [      new sap.dennisseah.IconNumIndicator({        src: 'sap-icon://email',        value: 10      }),      new sap.dennisseah.IconNumIndicator({        src: 'sap-icon://task'      }),      new sap.dennisseah.IconNumIndicator({        src: 'sap-icon://inbox',        value: 15      }),      new sap.dennisseah.IconNumIndicator({        src: 'sap-icon://action',        value: 2      }),      new sap.dennisseah.IconNumIndicator({        src: 'sap-icon://marketing-campaign',        value: 4      })     ]  });  ctrl.placeAt('content');
});

 

-D

Fiori Apps selbst gemacht mit der neuen SAPUI5 Design rapid-deployment solution!

$
0
0

Original Blog by Bob Caswell in English, here my translation, endorsed by the author.


FioriFlower.png

Für die Uneingeweihten, lasst mich zunächst einen knappen Überblick geben, was mit Rapid Deployment Solutions (kurz RDS) gemeint ist: RDS bieten eine schnelle und
einfache Methodik zum Implementieren von SAP Produkten. Schritt-für-Schritt Leitfäden, Musterlösungen, Schablonen, und Werkzeuge sorgen für vorhersehbare
Projektumfänge, -zeiträume, und -ergebnisse. Kurz, verglichen mit herkömmlichen Implementierungsmethoden sparen RDS im Schnitt zwischen 20 und 80% Zeit und Kosten ein.

Wohlbekannt sein dagegen dürfte die wiedergefundene strategische Besinnung der SAP auf Anwenderfreundlichkeit (UX, für User Experience) ihrer Produkte, mit den ikonischen Fiori Apps, und SAPUI5. Zur Unterstützung dieser Strategie tragen eine Reihe neuer RDS Pakete für Anwenderfreundlichkeit bei, von denen ich heute eines herausstellen möchte, die Lösung SAPUI5 Design rapid-deployment solution. Mit diesem Paket macht SAP dieselben Vorgehensweisen, die sie intern zum Gestalten ihrer Fiori Apps verwendet, erstmals dem breiten Publikum von Kunden, Partnern und freien Entwicklern zugänglich, so dass nun jeder eigene transaktionale Apps im Fiori Stil selbst gestalten kann. 

 

Der Name “SAPUI5 Design RDS” kommt vom SAPUI5, dem betriebssicheren HTML5-Derivat der SAP, deren Libraries die Firma für die Anwenderoberflächen ihrer Fiori Apps verwendet. Dieses RDS Paket folgt den Fiori Gestaltungsmustern und zeigt auf, wie Sie Ihre eigenen Apps im gleichen Stil und mithilfe derselben Methodik selber machen können. Wichtig dabei: Fiori ist nicht etwa ein blumigerer Name für SAPUI5, sondern ein eigenes Design Paradigma, mit sehr spezifischen Anforderungen an das Look-and-Feel der Apps.

 

Sie fragen wie sie an dieses RDS Paket herankommen können, und Fiori Design Gestaltungsprinzipien für ihre Projekte nutzen können? Ganz einfach: Mit Ihrem S-User auf dem SAP Service Marketplace anmelden und das Paket runterladen. Dazu sollten Sie in ihrem Browser Pop-ups gestatten, und den SAP Download Manager installiert haben (ein Link zum Runterladen findet sich im Pop-up Fenster). Im Pop-up Fenster auf „Installation“ klicken (bei manchen Benutzern mag eine „Authorization“ Meldung erscheinen, die getrost ignoriert werden kann; der „Installation“ Link wird schon tun). Und dann einfach den Anweisungen im Fenster folgen um die ZIP Datei herunterzuladen. Extrahieren Sie die ZIP Datei in einem Verzeichnis Ihrer Wahl.  

 

Innerhalb Ihres Verzeichnisses der extrahierten Dateien doppelklicken Sie auf die Datei mit dem hübschen Namen RDS_SAPUI5_NW731V1_STND.htm. Damit öffnen Sie den Schritt-für-Schritt Leitfaden in Ihrem Browser, der sie durch die typischen Projektphasen führt: Vorbereitung, Anforderungen, Umfang, usw. mit sogenannten Beschleunigern, die sich rechter Hand unter “Accelerators“ finden. Wenn Sie sich von links nach rechts durch die Projektphasen durchklicken, gelangen sie irgendwann zum Schritt „Deploy: Train Key Users“, mit einem Bereich unter dem Namen „Content Library“ auf der rechten Fensterseite. Wenn Sie darauf klicken, öffnet sich ein weiteres Fenster mit einer Liste sogenannter Bausteine, „Building Blocks“ (siehe Abbildung unten), die die Musterlösungen und Schablonen dieses Pakets enthalten.      

SAPUI5_Design_RDS_Blog.png

 

Baustein "U55: SAP Fiori Design" enthält die Fiori Design Richtlinien, mit Musterlösungen, geordnet in SAP Fiori Prinzipien, SAP Fiori App Typen, SAP Fiori Muster, Komponenten und Controls. Der Anhang enthält Details der Fiori Typografie, Farbschemata, und Ikonen. Falls Ihnen der Weg über den Schritt-für-Schritt Leitfaden zu beschwerlich erscheint, hier eine Abkürzung: In Ihrem Verzeichnis der extrahierten Dateien folgen Sie der Verzeichnisstruktur SAP_BP -> BBLibrary -> Documentation  und suchen Sie nach der Datei die mit „U55“ beginnt. Dort finden sich auch die anderen oben aufgeführten Dateien. 


Womöglich sollte ich den Link zum sogenannten SAPUI5 Design RDS "Quick Guide" noch anführen, der Anleitung gibt zum Aufsetzen der Fiori Entwicklungsumgebung („SAP Fiori Integrated Development Environment“).

Und schließlich noch ein Hinweis: All diese Dokumente bilden eine Art Selbstlernkurs zum Kreieren von Fiori-artigen Apps. Wenn Sie dagegen eher an der Dienstleistungsvariante des RDS Pakets interessiert sind, das einen UX Design Thinking Workshop umfasst, mit praktischen Übungen, und eine Machbarkeitsstudie für Fiori-artige Apps, finden und drücken Sie im SAP Store einen orange-farbenen Knopf „Mich kontaktieren“.


Für Fragen oder Kommentare verwenden Sie bitte die Kommentarfunktion unten.

 

Viel Erfolg beim Entwerfen vieler neuer Fiori Apps!

Discovering the Browser Console command line with SAPUI5 / OpenUI5

$
0
0

In this blog I want to show you how can be useful the Javascript Console when we are working with SAPUI5  / OpenUI5.

Of course for an experienced Javascript developer it can be an obvious consideration but for all ABAPers which are trying to learn Javascript and SAPUI5  the javascript command line could be a useful discovery.

 

On a similar topic ("Javascript for Abapers") I want to suggest 2 interesting blogs:

 

In every web-page we can run Javascript and in every browser there is a Console to play with it!

So using the console I can execute Javascript statements to explore objects , overwrite them,  adding functionalities to the JS project and so on.

 

How can I open the javascript console?

I really like Firebug console (http://getfirebug.com) and I'm going to use it for all my examples but you can try to open the Console with your favorite browser :

 

  • Chrome : CTRL + SHIFT + J
  • Firefox : CTRL + SHIFT + K
  • Firebug (a Firefox add-on) : F12
  • IE : F12
Now I can execute javascript expressions with an autocomplete feature of all objects! (and using TAB we can accept the suggestions);

 

 

Let's start opening the following url from the official openUI5 doc and opening your browser console,now we are ready to execute Javascript statements.

https://openui5.hana.ondemand.com/content/Examples/databinding.html

 

01_Intro.JPG

 

What is the current SAPUI5 version?

 

sap.ui.version

 

02_sapui_version_01.jpg

02_sapui_version_02.jpg

 

The current SAPUI5 version is 1.18.11

(you noticed how it can be useful the autocomplete feature of the console)

 

 

Getting the value of the Input Element with id "txtField"

we can explore the same input element in different ways:

  • as a standard DOM Object (without using frameworks)
  • as a jQuery object (SAPUI5 core contains jQuery )
  • a a SAPUI5 object instance

 

DOM Object

 

document.getElementById("txtField").value

03_DOM_value_01.jpg

03_DOM_value_02.jpg

and of course we get the value "John"

 

jQuery Object

we can get the same value using jQuery , the global jquery variable is the dollar sign ($) : with the $( "#id" ) statement we can select a single element with the given id attribute.

 

$("#txtField").val();

 

We used val() and not val because it's a jQuery function and not an attribute

04_jQuery_value.JPG


SAPUI5 Object

Finally we can try to use SAPUI5 to get the "John" value: we can define a new variable "oInputField" to get the instance by the ID and then exploring the instance;


 var oInputField = sap.ui.getCore().byId("txtField");
//we can use getValue() or getProperty("value") it's the same
oInputField.getValue();
oInputField.getProperty("value");

05_SAPUI5_value_01.jpg

05_SAPUI5_value_02.jpg


Getting the model data

Using the "oInputField" of the previous example we can get the current model bound to the object with:


oInputField.getModel().getData();

The method returns an object with the model data that we can easily exploring with a click

06_Model_01.JPG

06_Model_02.JPG

 

If I want to get the model data as JSON string I have to use another method:

 

oInputField.getModel().getJSON();

06_Model_03.JPG

Getting the binding path of the property "value"

We got the model data but I want to know if the value "John" is bound to the model (Ok , I read the JSON property firstName:"John" but I' want to check if the value of the input field is bound to the property "firstname")

 

I can use the method getBindingPath

 

 

oInputField.getBindingPath("value");

 

06_Model_04.JPG

The property "value" of the input field is bound to the "firstname" attribute of the model data, now we can try to overwrite the model

 

Overwriting the data model

we can try to overwrite "firstName" property and check if the value is correctly updated to the input field value using the "setData" method.

 

oInputField.getModel().setData({"firstName":"Alessandro"},true);

We replaced the data! the value was correctly updated with the new value "Alessandro"

 

06_Model_05.JPG

 

 

I passed a second additional parameter "true" because I don't want to overwrite the whole object but just merging the data

 

from the documentation:

setData(oData, bMerge?)

 

Sets the JSON encoded data to the model.

Parameters:

{object}    oData    the data to set on the model

{boolean}    bMerge?, Default: false    whether to merge the data instead of replacing it

 

Define a new object and overwrite the model (without merging)

we can use the default "no merging" option for overwriting the model defining a new object.

I'll try to overwrite the property "enabled" of the model bound to the property "enabled" of the input field and to the property "checked" of the checkbox , so If I set the data model property"enabled" to false both the controls will change from "editable" to a "non editable" state

 

var newDataModel = oInputField.getModel().getData();
newDataModel.enabled = false;
oInputField.getModel().setData(newDataModel);

06_Model_06.JPG

 

 

that's all!

of course possibilites are endless...

As always all feedbacks , comments and suggestions are welcome

Combining SAP UI5 with D3js to display the results of an algorithm

$
0
0

Hi, everybody.

 

I just wrote something about using a combination of SAP UI5 and the D3js library.

 

When you need a more advanced visualization, like graphs for example, you can't do it with the actual tools; but you can code and make a valid customization in order to get it.

 

I'm using a SAP HANA Predictive Analysis Library algorithm. This is the Link Prediction algorithm, and it works with graphs and relations between entities. The result: another graph.

 

In this blog, you can read and get all the code and necessary files.

 

Hope you like it.

Navigate between two Views in SAPUI5 Using Destroy Method

$
0
0

Hi All,

 

In View Page 1 : Create one Button using below code

var butt = new sap.ui.commons.Button({

id : "id-butt",

text : "Submit",

press : oController.Submit

});

 

 

In Controller Page 1 :

 

Submit : function(){

//navigating between two views

 

var view1 = sap.ui.view({id:"idview12", viewName:"sapui4_firstprogram.Vs", type:sap.ui.core.mvc.ViewType.JS});//Initialize New View here
view1.placeAt("content");
var r = new sap.ui.getCore().byId("idview11");//By using this to call view 1
r.destroy();// Destroy the first View

 

}

 

Now First View will Destroy and you Can easy to navigate to Second View in a Single index Page...

 

Thanks,

Karthik A

Responsive Design of UI5 SplitApp

$
0
0

This post shows the Responsive Design feature of UI5 SplitApp (sap.m.SplitApp) respectively SplitContainer.

It is both valid for OpenUI5 and SAPUI5. I will demonstrate this awesome feature with the UI5 Boilerplate (...what else? of course ) on different devices (iPhone and iPad) and with Chrome (desktop use case).

 

You can also try this yourself with your iPhone, iPad by simply browsing the UI5 Boilerplate Demo Site: UI5 Boilerplate SplitApp

or you check out the source code form the GitHub Repo: 6of5/UI5SplitApp-Boilerplate · GitHub

 

Ok let's start from big to small:

 

Case 1: iPad - Master and Detail

On an iPad or tablet the SplitApp shows both the Master and Detail page (right part) and the same time:

UI5BPoniPadA.jpg

 

Case 2: iPhone - Master or Detail

On an smartphone the behaviour is different. There only the Master or Detail page is shown at a time. On Detail pages additionally a back button is displayed on the left upper corner to be able to navigate back to the Master page.

 

IMG_0736.jpgIMG_0740.jpg

 

Case 3: Desktop - it depends!

In the browser (Chrome, Firefox, Safari or IE9+) the design depends on the available size of the browser window. When there is enough space both Master and Detail page are shown:

UI5RespDesignDesktop1.jpg

Navigation to another Detail page is done via the Master page, which is then marked as selected:

UI5RespDesignDesktop2.jpg

 

But if you resize the window and make it smaller the layout/design is changed. Only the Detail page is shown and you got additionally a icon in the upper left corner to open the Master page as a popover to be able to navigate to other Detail pages:

 

UI5RespDesignDesktop3.jpgUI5RespDesignDesktop4.jpg

 

What do you need to do to realise Responsive Design?

Not much, the SplitContainer is doing most of the magic out of the box. Fantastic, or!?!!!

Behaviour which is special for a use case needs to be implemented individually and tested!.

 

To support different platforms, it is common, to introduce a device model in the app:

Code1.png

Depending on the device model special behaviour can be implemented per platform, e.g. to realise the back button for the smartphone use case:

Code2.png

Have a look in the UI5 boilerplate source code for all details, it is available on GitHub: 6of5/UI5SplitApp-Boilerplate · GitHub

 

 

Create a App Icon on the home screen!

You can also make a nice Icon for this Web App on the home screen. Following the steps on the iPad, on the iPhone it should be pretty much the same. First press the share button (sorry screenshot are in german):

UI5BPoniPadB.jpg

Confirm or change the Icon name:

UI5BPoniPadC.jpg

As result you get a new Icon the home screen, with which you can start the web app directly, without typing in the url:

 

UI5BPoniPadD.jpg

 

 

 

Note: The UI5 Boilerplate should also work for Android and BB10 smartphones (I have not tested it yet).

 

Additional information


The Search for Atlantis: Choose your own UI Adventure

$
0
0

What is the Search for Atlantis

A while ago, a few of us came together to "search for Atlantis". If you want to know more about this now dormant initiative, check out the article in the SAP Mentors Quarterly - Q1 2011 but in a nutshell, it's trying to get conversations happening within the SAP ecosystem about both SAP and non-SAP topics that are undergoing a lot of change that people should be aware about.  Plus, where possible providing some guidance since we all love hearing "It Depends" from our SAP consultants. Anyway, I've revived the name for a blog about UI but I'm happy for others to "search for Atlantis" with us and write their own blog posts under this banner (or not). 

 

Choose your own UI Adventure

Some of the older or nostalgic people out there may remember the fad that was choose your own adventures back in the 80’s and this blog is dedicated to that medium to help explain the adventure that is User Interface development in SAP.

 

As with all content on SCN, be aware that this is very rough advice based on my experience/exposure and while I hate “it depends” answers, there’s definitely devil in the detail around defining strategies and most of below is only a fraction of the questions that really should be asked. e.g. I’m brushing over things like Portal, Mobility, non-ABAP back-ends, latency issues, etc.

 

Anyway let’s begin (hopefully I didn't miss an ending as these are tough to write!?!):

 

- Page 1 -

The date is the 15th of April, 2014 and it’s your first day at “We Do Stuff Good” INC/Pty Ltd and you’re brought into the board room and the CEO has asked you to define a UI technology strategy for development of a large new solution within an existing Portal they are urgently needing to build.


If you say, “Okay, I’m done. Thanks but no thanks!” turn to Page 2.

If you say, “I’ll get right on it” turn to Page 3.

- Page 2 -

You live happily ever after.

 

- Page 3 -

You go back down the elevator from floor 50 down to the basement where your team is and start asking questions.

 

If you discover that you don’t have SAP and never will have for this project, ironically turn to Page 2.

If you have SAP turn to Page 4.

- Page 4 -

You find out the solution is interfacing directly with your SAP ERP 6.0x (ABAP) application data and there is no commercially available solution from anyone available in the next 12-24 months so buying is not an option, so you then ask whether the solution is for external users or for internal users.

 

If it is for external users, turn to Page 5.

If it is for internal users, turn to Page 6.

- Page 5 -

Because these new external users are not licensed under any existing product and there is no off the shelf online solution available, you say “okay, I’ll need to use NetWeaver Gateway if only to give us an easy way to expose the SAP side to these users”. The others sigh and agree.


If the external users are trusted users that you can dictate client requirements to and there's no company push to get SAPUI5/Gateway in place, and people upskilled ASAP, then turn to Page 19.

If the external users are not a easily controlled set of users, turn to Page 6.

- Page 6 -

You ask to see the web development team to get more information about their existing tools, processes, etc.

 

If they say, “Good idea, anything externally facing is developed by this team”, go to page 7.

If they say, “There is no web development team, just us”, or “that team is only used for the marketing website and don’t touch application development” go to page 8.

- Page 7 -

You meet up with the lead from the web development team and you ask about the team’s background and how they currently development solutions.

 

If the lead says, “We’re mainly a Microsoft shop and use Visual Studio and Team Foundation Server tools though leverage Open Source where appropriate”, turn to Page 9.

If the lead says, “We’re mainly an Open Source shop and each developer has their own favourite editor, but we've standardised on our frameworks and deployment/test automation”, turn to Page 10.

- Page 8 -

So you’re pretty sure you know what to do, but one question remains; is this an application that needs to be lightning fast around the globe, not be bandwidth hungry at all or need to support...wait for it...IE8 or less .

 

If yes, turn to Page 11.

If no, turn to Page 25.

- Page 9 -

 

If the lead also stated, “we are using Odata already and also leveraging one of the JavaScript framework libraries included in Visual Studio", turn to Page 12.

If the lead alternatively says, “we aren’t doing anything with Odata yet and are not fixed on one set of web frameworks”, turn to Page 13.

- Page 10 -

Introduce SAPUI5 (or openui5 more importantly), and discuss whether it could be the framework for SAP development since it provides better capabilities with leveraging odata

 

Turn to Page 2.

- Page 11 -

Engage your Web specialists to ensure they build a supportable framework and appropriate Content Delivery Network topology to build your solution in, leveraging Gateway for service calls. Make sure that the team is still aware of the capabilities of SAPUI5 just in case.

 

Turn to Page 2.

- Page 12 -

Introduce SAPUI5 (or openui5 more importantly), and discuss how it could be of use, and stick to the existing frameworks if appropriate and current.

Turn to Page 2.

- Page 13 -

Introduce SAPUI5 (or openui5 more importantly), and discuss whether it could be the framework for SAP development since it provides better capabilities with leveraging odata.

Turn to Page 2.

- Page 14 -

This page intentionally left blank

- Page 15 -

You realise that without knowing more about the solution’s requirements, you will be generalising way too much with technology decisions, so you ask about the personas and the scenarios being supported.

 

If you find out it is more a tool of the trade where people will be solely using this day in/day out to do their job including outside the office, sometimes without network access, turn to Page 16.

If you find out it’s more an online scenario combined with many other online scenarios, turn to page 24.

- Page 16 -

You realise you are heading down the path of an offline SAP Mobile Platform based solution such as Agentry, or possibly a Kapsel wrapped UI5 application with offline storage. You set the strategy, but say we’ll need to get to the bottom of the solution before going much further down a specific path.

 

Turn to Page 2.

- Page 17 -

You are starting to see a real opportunity here so you ask whether they have Fiori elements like Gateway in place already or desire to do so; and whether they are interested in the development team learning HTML, CSS and JavaScript.

 

If they disappointingly say they don’t have anyone who wants to learn that stuff, and like staying in the ABAP world, turn to page 19.

If they are all for the (current) future of UI development in SAP, then thankfully turn to page 18.

- Page 18 -

You settle on SAPUI5 for your UI technology strategy (amongst many other things), and start thinking about the security requirements, and mobility aspects required for the solution also. Also, you get support from the CIO to hire a UX specialist/UI Designer who is also very comfortable with HTML/CSS to ensure solutions are a joy to use and also help out the dev team with the transition to the web world.

 

Turn to page 2.

- Page 19 -

Slightly frustrated, you ask whether they have FPM skills?

 

If they say, “sure”, or “We know Web Dynpro, so let’s learn FPM since that’s also a strong UI development direction from SAP”, turn to page 20.

If they respond, “No and we don’t want to learn FPM”, turn to page 21.

- Page 20 -

You settle on FPM for your solution, realising that you’re really limiting mobile scenarios and such, but at least we can revisit the strategy in another year to see whether things have moved on.

 

Turn to Page 2.

- Page 21 -

You ask, “Um, do you at least have Web Dynpro Skills”?

 

If they respond, “Nope – Why would we want to learn that?”, turn to Page 23.

If they respond, “Yes – Of course!”, turn to Page 22.

- Page 22 -

You settle on Web Dynpro for your solution, realising that you’re really limiting mobile scenarios and such, but at least we can revisit the strategy in another year to see whether things have moved on.

 

Turn to Page 2.

- Page 23 -

You are in shock, and immediately go to the CIO to see about hiring a few A players and letting go any that don’t want to even learn new skills.

 

If the CIO does not console you or even understand the problem, you immediately quit – Turn to Page 2.

If the CIO consoles you but cannot change the team in the short term, turn to Page 27

- Page 24 -

You immediately realise that a lot will depend on the target clients, so you ask about mobiles, tablets and desktops; focussing on aspects that point to responsive or mobile design requirements.

 

If they respond with, “Only desktops in the corporate environment”, turn to page 17.

If they respond with, “Definitely a responsive design that can run on any client is required”, turn to page 25.

- Page 25 -

You realise that regardless of the team's capabilities and desire to learn, it is time to get up to speed on SAPUI5, Gateway and possibly SMP and Kapsel depending on mobile deployment requirements. Also, you get support from the CIO to hire a UX/UI Designer  specialist who is also very comfortable with HTML/CSS to ensure solutions are a joy to use and also help out the dev team with the transition to the web world.

 

Turn to Page 26.

- Page 26 -

After a lot of effort in getting everyone up to speed, including change management and potential hiring and reorganisations, you live happily ever after (till the next SAP UI revolution comes along).

 

- Page 27 -

You decide to get SAP Screen Personas product and somehow come to grips to put forward a strategy to use SAP Dialogue programming; and try to live happily ever after.

- Page 28 -

I dedicate this book to the SCN Community who will shred into any opinion in this book that is unfounded or sometimes founded usually in the hope of making our community a better place to be, and to make our day jobs just that little bit better.

- Page 29 -

The End

Quick workaround to solve issue regarding oData CRUD in Latest Chrome!

$
0
0

Hey All,

 

If you get an error as below when your do any CRUD operations using oDATA ,

 

oData.JPG

 

Open your console and execute the below code & check if your app works (don't refresh after executing this code in console) https://gist.github.com/arv/9529994

 

if (!Document.prototype.createAttributeNS) {  Document.prototype.createAttributeNS = function(namespaceURI, qualifiedName) {   var dummy = this.createElement('dummy');   dummy.setAttributeNS(namespaceURI, qualifiedName, '');   var attr = dummy.attributes[0];   dummy.removeAttributeNode(attr);   return attr;  };
}
if (!Element.prototype.setAttributeNodeNS) {  Element.prototype.setAttributeNodeNS = Element.prototype.setAttributeNode;
}

 

If your app works like a charm , then the reason for the above error is just because Chrome has remove some DOM Level 2 API's. Internally data.js uses two functions

 

          document.createAttributeNS() ,  document.setAttributeNS()

 

which have been removed from chrome's API. The workaround code would manually add those functions to the DOM object document.

 

So, till this is fixed you can create a new js file say, workaround.js and copy the code posted above and import it to your ui5 app index.html as

 

<script src="workaround.js"></script>

 

Once this issue is resolved, you can remove the workaround script This is just one of the workaround available.

 

Regards

Sakthivel

Wanted: UI5 developers. UI5 is mandatory, JavaScript is optional

$
0
0

Hello All,

 

Our org. is in need of UI5 developers. The requirement is clear. The candidate should be able to develop using UI5. Then, on query about the need to know JavaScript, the team's reply, ' JavaScript? Not required'. I went silent and then remained silent.

 

The topic came across yesterday during my conversation with one of the team member, who shared the experience. I was just wondering, why do we always make the mistake of falling for the same trap or the same marketing gimmick. To clarify, I am not saying UI5 is a gimmick. Its just that we always tend to fall for the keywords.

 

UI5 is nothing more than a set of JavaScript libraries which are made available as open source by SAP. Its not a new language neither a new specification by SAP. Its just a set of features on top of existing web technology.

 

JavaScript is at the core of the development. The client side scripting language which has literally come to the fore front, is the actual engine behind the new user interface. In collaboration with HTML5 and CSS they form the trio of modern web technologies. UI5 is nothing more than set of SAP toolset on top of the trio. Its like an external API/JAR which is used within the existing framework.

 

To perceive UI5 as a new language the team leads make the mistake of giving importance to the terminologies. The fundamentals of JS are more important to the developer rather than the jargon. The technical terms can be adapted to by the developers in a few days. But, to have one without the necessary fundamentals, we risk giving another half-baked solution. Later, we blame the developer for not being good enough. Well, where was the wisdom of the team when the skill was identified based on the outer branding rather than the actual fundamentals.

 

We should give more impetus in using the technology trio and use the UI5 libraries to facilitate the SAP specific solution. The former is the key, the latter is an assist. Let us not mix it up, Once Again.

 

Best Regards,

Sharath

Logoff/Logout function for a UI5 Apllication

$
0
0

Though I have been working on UI5 for sometime, I had never explored Logoff functionality. I always thought that it would be as simple as calling an API and redirecting to a logoff page. Once I started, there were so many hurdles and I got to learn a great deal about cookies and authentication. I am sharing this experience in implementing a “Logoff” functionality for a UI5 application. My aim of writing this blog is to share the learning as well as to explore if there are better approaches. Source: Numerous posts on stackoverflow.com

 

Set Up: UI5 application hosted in a Basis 740 SP5 system as NW Gateway server. 

 

Loging off a user involves two steps

1. Invalidating the SSO cookies.

2. Deleting the Authentication cache stored by the browsers

 

Step 1. Invalidating the SSO cookies.

I learned that SAP provides a logoff service which can clear the SSO cookie in the browser. This is a service stored under 'public' node. When called as a GET request, this service returns set-cookie headers as response headers with an expiration date in the past. Browser, on receiving the set-cookie, sets these values with the current SSO cookies, thus invalidating them. If you are using a different server to host your UI application, check the documentation to find a similar logoff service.

 

Step 2. Deleting the Authentication cache stored by the browsers

This step differs from browser to browser. Always abused IE :-) does a better job by providing a javascript API to this task. For other browsers, you need to make a call to the server with dummy credentials so that browser receives a “401-Unauthorized” which forces the browser to delete the stored authorization headers. Again ever useful jQuery provides a call back function to handle 401 error so that user is not shown an awkward authorization credentials pop-up.

 

Below is the code I arrived at. I have only tested on latest versions of Mozilla, Chrome and IE. Also only Basic Authentication scenarios has been tested. Let me know your ideas and suggestions to improve this.

 

function logoff(){       $.ajax({           type: "GET",           url: "/sap/public/bc/icf/logoff",  //Clear SSO cookies: SAP Provided service to do that        }).done(function(data){ //Now clear the authentication header stored in the browser                            if (!document.execCommand("ClearAuthenticationCache")) {                                 //"ClearAuthenticationCache" will work only for IE. Below code for other browsers                                 $.ajax({                                               type: "GET",                                               url: "/sap/opu/odata/SOME/SERVICE", //any URL to a Gateway service                                               username: 'dummy', //dummy credentials: when request fails, will clear the authentication header                                               password: 'dummy',                                               statusCode: { 401: function() {                                                         //This empty handler function will prevent authentication pop-up in chrome/firefox                                               } },                                               error: function() {                                                    //alert('reached error of wrong username password')                                               }                                });                            }        })
}

SAPUI5 PDF Viewer (SmartForms) Custom Control

$
0
0

A while back ChandrashekharMahajan wrote a great blog on the ways to show PDF in a SAPUI5 application Display Smartform (PDF) in SAPUI5

 

I mentioned that we used the same approach for our own product FLM, which renders both PDF (SIFbA) and also HTML Based Forms.  And that I was looking to wrap this solution up in a stand alone control.

Well it taken me a little bit longer than a few weeks to find the time to do this, but I have now written the start of this control and the below shows the control set-up.

 

The Eclipse Project is on gitHub and can be located here https://github.com/MartinJCook/PDFViewerUI5

 

This means to display a PDF, all you need now are a few lines of code.

var objPDF = new PDFViewer("myPDF");


//Set the PDF Viewer Control with the content via a URL
objPDF.setPDFurl("http://www.adobe.com/content/dam/Adobe/en/company/pdfs/fast-facts.pdf");

 

 

The Custom Control allows PDF to be displayed both via a URL link or by a BASE64 embedded string.  NB That IE does not support BSE64 embedding.

 

The Below shows the properties of the control, where either the URL or the BASE64 string can be set, as well as the width and height of the PDF Viewer

 

"PDFurl" : "string",

"PDFBase64" : "string",

"width" : {type: "sap.ui.core.CSSSize", defaultValue: "600px"},

"height" : {type: "sap.ui.core.CSSSize", defaultValue: "700px"}       

 

Internally the control uses a HTML Control to define and render a iFrame window as shown by the below aggregations

 

_HTMLContainer: {type : "sap.ui.core.HTML", multiple : false, visibility: "hidden"},

 

Then on initialization on the control we embed an iFrame into the HTML Container

 

var oControl = this;
var oHTML;


oHTML = new sap.ui.core.HTML({
});


//Now embed the iFrame
var iframeID = this.sId + "iFrame";   
oHTML.setContent("<iframe id='"+ iframeID + "' width='100%' height='100%'></iframe>");


this.setAggregation("_HTMLContainer", oHTML);

 

Then when either the URL or BASE64 code is set we locate the iFrame on the DOM and update the src using jQuery as shown below


With the BASE64 we set the src attribute in the following way  <iframe src="data:application/pdf;base64,base64encodedpdf"></iframe>

 

//overwrite setter for the Set PDF URL
PDFViewer.prototype.setPDFurl = function (sVal) {
      //Now get the iFrame element inside the
      var iframeID = this.sId + "iFrame";


      //Now update the value and also set the source in the iFrame element
      //With the URL to the PDF
      if (sVal) {
          this.setProperty("PDFurl", sVal, true);

 
          //Now set the iFrame src to the URL
          jQuery.sap.byId(iframeID).attr('src', sVal)
    }
};


//overwrite setter for the Set PDF BASE64
PDFViewer.prototype.setPDFBase64 = function (sVal) {
      //Now get the iFrame element inside the
      var iframeID = this.sId + "iFrame";


      //Now update the value and also set the source in the iFrame element
      //With the actual base64 PDF
      if (sVal) {
            this.setProperty("PDFBase64", sVal, true);

 
            //Now set the iFrame src to the BASE64 PDF data
            var srcURL = "data:application/pdf;base64," + sVal;
            jQuery.sap.byId(iframeID).attr('src', srcURL)

      }
};

 

 

This is just a working example and I sure it can be improved/tweaked, in fact it took longer to write this blog than to actually write the control

 

Please feel free to make suggestions/improvements and share.

 

Martin

Small workaround for TextArea change when inside an InPlaceEdit

$
0
0

Hi,

If you've been using InPlaceEdit with a TextArea you probably noticed that it has stopped responding to changes.

This is due to recent changes which are described here.

 

If you still want to leverage the benefits of TextArea combined with InPlaceEdit, a simple workaround can be used.

 

After defining a textArea control with a change function:

 

textArea.attachBrowserEvent("blur", textArea.onsapfocusleave);

textArea.onsapfocusleave = function(){

textArea.fireChange();

        };

 

Have fun.

byg.

Displaying backend data both as SAPUI5 Table and an Excel File

$
0
0

Introduction -

 

Most of the time we need functionality to download table content in the form of excel file. There is no standard way to achieve this on sapui5 table control.

This excellent blog Export sap.ui.table.Table as CSVby Angel Puertastalks about exporting the table content in the form of CSV file and it is generated on

client side.

 

In my current blog, I will share details of generating excel file in the backend and then downloading it in frontend UI5 application.


I am going to develop UI5 application showing details of standard SAP table SAIRPORT in ui5 table and will provide export button to download table content.


Procedure -

 

First, we need to develop FM, lets call it as Z_TEST_XLS_DISPLAY. The logic is as explained in below code.

FUNCTION Z_TEST_XLS_DISPLAY.

*"----------------------------------------------------------------------

*"*"Local Interface:

*"  EXPORTING

*"     REFERENCE(E_URL) TYPE  STRING

*"----------------------------------------------------------------------

 

* Data Declaration

  DATA :

  lv_app_type        TYPE string,

  lv_guid            TYPE guid_32,

  lo_cached_response TYPEREFTO if_http_response,

  ls_airport_string  TYPE string,

  ls_airport_xstring TYPExstring,

  lt_airport         TYPESTANDARDTABLEOF SAIRPORT,

  ls_airport         LIKELINEOF lt_airport,

  ls_file_name       type string.

 

*Get data from SAIRPORT table

  SELECT * FROM SAIRPORT INTOTABLE lt_airport UPTO50ROWS.

 

CONCATENATE ls_airport_string

                'Airport ID'   cl_abap_char_utilities=>horizontal_tab

                'Airport Name' cl_abap_char_utilities=>horizontal_tab

                'Time Zone'    cl_abap_char_utilities=>horizontal_tab

                cl_abap_char_utilities=>newline

                INTO ls_airport_string.

 

 

  LOOPAT lt_airport INTO  ls_airport .

    CONCATENATE ls_airport_string

                ls_airport-id         cl_abap_char_utilities=>horizontal_tab

                ls_airport-name       cl_abap_char_utilities=>horizontal_tab

                ls_airport-TIME_ZONE  cl_abap_char_utilities=>horizontal_tab

                cl_abap_char_utilities=>newline

                INTO ls_airport_string.

  ENDLOOP.

 

 

  CALLFUNCTION'SCMS_STRING_TO_XSTRING'

    EXPORTING

      text  = ls_airport_string

    IMPORTING

      buffer = ls_airport_xstring.

 

 

CREATEOBJECT lo_cached_response

    TYPE

    cl_http_response

    EXPORTING

      add_c_msg = 1.

 

****set the data and the headers

  lo_cached_response->set_data( ls_airport_xstring ).

  lv_app_type = 'APPLICATION/MSEXCEL; charset=utf-8'.

 

  lo_cached_response->set_header_field( name = if_http_header_fields=>content_type

                                     value = lv_app_type ).

****Set the Response Status

  lo_cached_response->set_status(code = 200 reason = 'OK').

 

****Set the Cache Timeout - 60 seconds - we only need this in the cache

****long enough to build the page

  lo_cached_response->server_cache_expire_rel( expires_rel = 60).

 

****Create a unique URL for the object and export URL

 

CONCATENATE'export_' sy-datum sy-uzeit INTO ls_file_name.

CONCATENATE  '/sap/public/'  ls_file_name '.''xls'INTO e_url.

 

****Cache the URL

  cl_http_server=>server_cache_upload( url     = e_url

                                       response = lo_cached_response ).

 

ENDFUNCTION.

 

Basically, we are getting data from table SAIRPORT and converting it into XSTRING and then building unique URL pointing to excel file location.

 

Now we will create OData Service to read the Airtport data and url

ui5_xls1.jpg

We need to redefine method AIRPORTCOLLECTIO_GET_ENTITYSET as below

method AIRPORTCOLLECTIO_GET_ENTITYSET.

 

  DATA: lt_airport TYPESTANDARDTABLEOF SAIRPORT,

        ls_airport LIKELINEOF lt_airport,

        ls_entity   LIKELINEOF et_entityset.

 

*Get data from SAIRPORT table

  SELECT * FROM SAIRPORT INTOTABLE lt_airport UPTO50ROWS.

 

*Fill ET_ENTITYSET

  LOOPAT lt_airport INTO  ls_airport .

    ls_entity-id   = ls_airport-id.

    ls_entity-name = ls_airport-NAME.

    ls_entity-time_zone = ls_airport-TIME_ZONE.

    APPEND ls_entity TO et_entityset.

  ENDLOOP.

 

endmethod.

 

And XLSCOLLECTION_GET_ENTITYSET as below

method XLSCOLLECTION_GET_ENTITYSET.

data:   ls_entity   LIKELINEOF et_entityset,

        lv_url      TYPE string.

 

CALLFUNCTION'Z_TEST_XLS_DISPLAY'

IMPORTING

   E_URL        = lv_url       .

 

ls_entity-url = lv_url.

APPEND ls_entity TO et_entityset.

 

endmethod.

 

With this we are done with backend logic.

 

Now let's create UI5 application. Below is the code of UI5 application.

 

<!DOCTYPE HTML><html>  <head>  <meta http-equiv="X-UA-Compatible" content="IE=edge"><script src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js"  id="sap-ui-bootstrap"  data-sap-ui-libs="sap.ui.commons,sap.ui.table"  data-sap-ui-theme="sap_bluecrystal">  </script>  <!-- add sap.ui.table,sap.ui.ux3 and/or other libraries to 'data-sap-ui-libs' if required -->  <script>  //Root URL for the service  function getUrl(sUrl) {  if (sUrl == "")  return sUrl;  if (window.location.hostname == "localhost" )  {  return "proxy" + sUrl;  }  else  {  return sUrl;  }  }  var sURI = getUrl('/sap/opu/odata/sap/ZTESTXLS_SRV/');  oModel = new sap.ui.model.odata.ODataModel(sURI, false),  sap.ui.getCore().setModel(oModel);  // Airport Details Table  var oTable = new sap.ui.table.Table({             title: "SAPUI5 Table Export as Excel",  width: "60%",  visibleRowCount : 10,  selectionMode : sap.ui.table.SelectionMode.Single,  editable : false  });  //Create html instances  var html = new sap.ui.core.HTML();     //Set table toolbar buttons  oTable.setToolbar(new sap.ui.commons.Toolbar({  items : [ new sap.ui.commons.Button({  text : "Export",  icon:"https://sapes1.sapdevcenter.com/sap/public/bc/icons/s_X__XLS.gif",  press : function(oEvent) {      var sRead = "/XlsCollection" ;      oModel.read( sRead, null, null, true, function(oData, oResponse){         var fileURL =   'proxy'+ oData.results[0].url;              html.setContent("<iframe src=" + fileURL + " width='0' height='0'></iframe>");              html.placeAt("content");         },function(){             alert("Read failed");             });              }  })]  }));  oTable.addColumn(new sap.ui.table.Column({  label : new sap.ui.commons.Label({ text : "Airport ID" }),  template : new sap.ui.commons.TextField({ value : "{AirportID}" })  }));  oTable.addColumn(new sap.ui.table.Column({  label : new sap.ui.commons.Label({ text : "Airport Name" }),  template : new sap.ui.commons.TextField({ value : "{AirportName}" })  }));  oTable.addColumn(new sap.ui.table.Column({  label : new sap.ui.commons.Label({ text : "Timezone" }),  template : new sap.ui.commons.TextField({ value : "{TimeZone}" })  }));  oTable.bindRows("/AirportCollection");  oTable.placeAt("content");  </script>  </head>  <body class="sapUiBody" role="application">  <div id="content"></div>  </body></html>

 

End Result -


Now let's execute application. On click of Export button, file will get downloaded as below.

ui5_xls2.jpg


Here we can see the file content same as table content. Each time, if we click export button, new file will get generated with current date and timestamp as unique filename.

ui5_xls3.jpg


Closing Remarks -


With the simple technique of creating temporary URL for the Excel file and then exposing that URL through GW service, we are building SAPUI5 application to consume GW service. We are then setting src property of an iframe with this URL and setting this content to HTML UI element.

 

This approach is almost similar to display PDF files as explained in my earlier blog Display Smartform (PDF) in SAPUI5

 

If you have experience of working on Webdynpro ABAP ALV then you will notice that this kind of exporting data to excel is provided as standard feature. of course, it is not possible in Client Side UI5 Application.


Just to be consistent with WDA, I am naming my files as export_<sy-datum><sy-uzeit>.xls

 

Just in case, if you are eager to know, you can observe WDA ALV export functionality in the standard application accessible with

url http://<host>:<port>/sap/bc/webdynpro/sap/wdt_alv?sap-language=EN

 

Observe that if you run UI5 application on IE then it will open modal dialog for excel file whereas on Chrome, you can export multiple files.

 

As usual, Please feel free to put your comments/suggestions and any other way to export excel files from backend!


Happy Learning and Coding!


Preview & Print of SAPUI5 viz charts

$
0
0

SAPUI5 viz library provides us with a wonderful collection of HTML5 charts which are intuitive, rich and very responsive, but however in the standard offering it lacks the support for preview and print feature of the viz component.

 

This post describes a generic way of getting this to work. From the rendered viz chart, we extract the svg element that forms the chart, clone it and add it to a new HTML window/document. This does the magic for us.

 

Here we have a button and on its press action we have associated the logic for generating the preview and print of the chart. Code for the same is given below:

 

function previewprintChart() { //This method is the press handler for a button in the page that has the viz chart, or it could be some menuitem in the page.

var features = "";// You could provide features for the new window

                        var newWin = window.open('', 'newWin', features);

                        var topDoc = "<html><head><title>Print Preview</title>";

                        var metaDoc = "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\"><meta charset=\"UTF-8\"> </head>";

                        var endDoc = "</body></html>";

                        newWin.document.write(topDoc);

                        newWin.document.write(metaDoc);

                        newWin.document.write("<body>");

                        var s = new XMLSerializer();

                        var svg = $('#content’).find('.v-m-root')[0]; //where content is the DIV id of the viz chart

                        var svgPrint = svg.cloneNode(true);        

                        var svgStr = s.serializeToString(svgPrint);

                        newWin.document.write(svgStr);

                        newWin.document.write(endDoc);

                        newWin.document.close();//make html available for print

                        newWin.print();

            }

 

I guess there could be other ways of doing this probably better ways too, if so please share.

 

Hope this helps somebody!

 

Thanks for reading...

Adding Colors (functions) to UI5 Controls !

$
0
0

Hey all,

 

I find many have started to tinker the UI5 controls by adding custom css to it But the bottleneck here is, some find difficult to find the appropriate classes or choosing the right selector to target the controls So, to make life easier what if we create a function, say kind off a Plugin that provides additional functionality to all the controls. Say something like

                                           

                      i) control . changeColor("colorName");


What if this would change the color of the control you wish to ? Sounds simple and neat for someone who wants to play around with the control's css.

        

                   ii) control . addCustomStyle("className","CSS");

 

And for someone who wants a freedom to express their own css , they could directly assign a className along with the css to be applied.


So, As of now i've created those two functions which would apply the css directly to the controls. To get those functions, you'll have to add this code below, custom-ui5-plugin.js

 

                         

varstyle=document.createElement("style");  document.head.appendChild(style);  style.type = "text/css";  style.innerHTML = "";  var oDUmmy = new sap.ui.core.Control();  sap.ui.core.Control.prototype.changeColor = function(oColor){   style.innerHTML = style.innerHTML + '.' + oColor + '{background-color:' + oColor + ' !important;}';   this.addStyleClass(oColor);  }  sap.ui.core.Control.prototype.addCustomStyle = function(oClassName,oStyle){   style.innerHTML = style.innerHTML + '.' + oClassName + '{' + oStyle + ' !important;}';   this.addStyleClass(oClassName);  }


say you can copy this code into a file "myCustomPlugin.js" and add it into a script tag once you have the bootstrap script. <script src="myCustomPlugin.js"></script>.


That's it. All the controls you create will have additional functions  i)changeColor() ii)addCustomStyle()


Example, say you create a button & wanna change the color to red, you can do

 

var oButton = new sap.m.Button({text:"Sample"}); //create a button    oButton.changeColor("red"); // change the color of the button


You can find the snippet here JS Bin - Collaborative JavaScript Debugging&lt;/title&gt; &lt;link rel=&quot;icon&quot; href=&quot;http://static.jsbin.…


                                                                          redButton.JPG


This will be result that you would get. For now, color values in hex codes not supported

 

What if someone wanna add a gradient or any css of their own,you can use the function addCustomStyle. Below i have applied a gradient background to the control Page. 

 

var oPage = new sap.m.Page({title:"UI5 Plugin",enableScrolling:true ,content:[]}); // create a Page
oPage.addCustomStyle('gradient',' background: -webkit-radial-gradient(
40% 20%, closest-corner, #153458, #232 947)'); // Adding gradienbackground to Page

 

You can find the snippet here JS Bin - Collaborative JavaScript Debugging&lt;/title&gt; &lt;link rel=&quot;icon&quot; href=&quot;http://static.jsbin.…   


                   

page.JPG

 

 

 

Check out this snippet where i've combined all in 1 JS Bin - Collaborative JavaScript Debugging&lt;/title&gt; &lt;link rel=&quot;icon&quot; href=&quot;http://static.jsbin.…



                             All.JPG

 

I haven't added much of functionality, just started with it

 

 

Regards

Sakthivel

Journey to SAPUI5

$
0
0

In the world of technological innovations, sometimes it becomes so difficult to keep ourselves updated with the relevant technologies.  In this blog, I would like to share my story and the difficulties that I had faced during my first SAPUI5 application development and integrating the same with SAP system through XML/JSON models. 

 

There is so much information available in the web about the same, and sometimes it is very difficult to digest too much of information.

 

Problem 1:  To find out the structured content in web.

Though there are lots of documents and How To guides available, however, I still feel that it is not structured for beginners like me.  However, the following links turned out to be very useful. Anyone who wants to learn SAPUI5 should give the below links a glance.

  1. https://sapui5.hana.ondemand.com/sdk/ - This is very good starting point and specially SAPUI5 Runtime section clears much of the fundamentals required.
  2. After reading above, it makes more sense to develop Hello World application by following https://sapui5.hana.ondemand.com/sdk/#docs/guide/HelloWorld.html

 

Problem 2: Dealing with cross domain issues.

I was not aware of the problems that one can face by calling model service of SAP system from my local test environment. Googling and SCN helped me so much to understand the problem and provided me much needed input at right time. As modern browsers have same-origin policy and they don’t permit running java scripts from different domains because of web application security. Refer Wikipedia - http://en.wikipedia.org/wiki/Same-origin_policy

 

After setting response header field to “Access-Control-Allow-Origin:*” and Access-Control-Allow-Methods:GET', I found workaround to deal with SOP.


Problem 3: Dealing with XML/JSON Model

XML model proved to be quite easier to implement, however, the JSON was really tricky to implement. Due to restrictions, we cannot call the JSON directly from SAPUI5 Javascript and thus we have to use JSONP (JSON with padding) and a callback service.

Following AJAX query can be used to call the JSON service in your SAPUI5 project.

              var oModel = new sap.ui.model.json.JSONModel();

                $.ajax({

                     url: url,

                     method: "GET",      

                     jsonpCallback : 'getJSON',

                     contentType : "application/json",

                     dataType:'jsonp',

                     success: function(json) {

                                  oModel.setData({modelData: json});

                                  oTable.setModel(oModel);

                                  oTable.bindRows("/modelData");},                     

                     error: function(json) {

                           console.log(json);   }

                     }

                     );

 

To post the data back to SAP, we can use POST type as follows:

       var formData = {name:"test",age:"31"}; //Array                      

                           $.ajax({

                               url : url,

                               type: "POST",

                               data : formData,

                               success: function(response)

                               {

                                  console.log(response);

                               },

                               error: function (response)

                               {

                                  console.log(response);

                               }

                           });

                                 

This is my story of learning SAPUI5, feel free to share yours.                             

Circular Icons Group

$
0
0

In this blog, we show how to arrange sap.ui.core.Icon in a circle like a circular dialer.

 

CSS

.sap-dennisseah-circular-icons-group {  border: solid;  opacity: 0.9;  border-radius: 50%;
}

.sap-dennisseah-circular-icons-group-btn { 
  position: absolute;  display: table-cell;  opacity: 0.5;  padding: 5px;  border-radius: 100%;
}

.sap-dennisseah-circular-icons-group-btn:hover { 
  opacity: 1;
}

 

Javascript

  sap.ui.core.Control.extend('sap.dennisseah.CircularIconsGroup', {    metadata: {      properties: {        borderwidth: {type: "sap.ui.core.CSSSize", defaultValue: '50px'},        diameter: {type: "sap.ui.core.CSSSize", defaultValue: '100px'},        color: {type: "sap.ui.core.CSSColor", defaultValue: '#007cc0'},        btncolor: {type: "sap.ui.core.CSSColor", defaultValue: '#005990'}      },      aggregations: {        icons: {type: "sap.ui.core.Icon"}      }    },    _style: function() {      var styles = [        'height: ' + this.getDiameter(),        'width: ' + this.getDiameter(),        'border-color: ' + this.getColor(),        'border-width: ' + this.getBorderwidth()      ];      return styles.join('; ');    },            renderer: function(oRm, oControl) {      oRm.write("<div");      oRm.writeControlData(oControl);      oRm.addClass("sap-dennisseah-circular-icons-group");      oRm.writeClasses();      oRm.write(' style="' + oControl._style() + '">');      var icons = oControl.getAggregation('icons');      for (var i = 0; i < icons.length; i++) {        var icon = icons[i];        icon.addStyleClass('sap-dennisseah-circular-icons-group-btn');        oRm.renderControl(icon);      }      oRm.write("</div>");    },        onAfterRendering: function() {      var that = this;      function center() {        var element = that.$()[0];        var d = element.getBoundingClientRect();        return { cx: d.left + d.width/2, cy: d.top + d.height/2 };      }            var icons = this.getAggregation('icons');      if (icons.length === 0) {        return;      }      var angle = 0;      var borderwidth = parseInt(this.getBorderwidth().replace('px',''));      var width = parseInt(this.getDiameter().replace('px',''));      var center = center();      var step = (2*Math.PI) / icons.length;            for (var i = 0; i < icons.length; i++) {        var ic = icons[i];        var ic_obj = $('#' + ic.getId());        var iradius = Math.max(ic_obj.width(), ic_obj.height());        var base = ((width + borderwidth)/2);        var offset = (iradius/2) + 5; // 5 = padding        var x = Math.round(base * Math.cos(angle)) + center.cx - offset;        var y = Math.round(base * Math.sin(angle)) + center.cy - offset;        ic_obj.css('background-color', this.getBtncolor());        ic_obj.css('width', iradius + 'px');        ic_obj.css('height', iradius + 'px');        ic_obj.css('left', x + 'px');        ic_obj.css('top', y + 'px');        angle += step;      }    }  });

 

Example

The control can be created in this manner where you have a bunch of icon and their actions (when being pressed.

  var ctrl = new sap.dennisseah.CircularIconsGroup({    icons: [      new sap.ui.core.Icon({        src: 'sap-icon://globe',        size: '25px',        press: function() {          alert('global');        }      }),      new sap.ui.core.Icon({        src: 'sap-icon://business-objects-explorer',        size: '25px',        press: function() {          alert('explorer');        }      }),      new sap.ui.core.Icon({        src: 'sap-icon://log',        size: '25px',        press: function() {          alert('log');        }      }),      new sap.ui.core.Icon({        src: 'sap-icon://world',        size: '25px',        press: function() {          alert('world');        }      }),      new sap.ui.core.Icon({        src: 'sap-icon://settings',        size: '25px',        press: function() {          alert('settings');        }      })    ]  });

 

Here is an example. and here is how it looks like

 

screenshot.png

 

 

-D

SAPUI5 Tip: How to make an animation progressing bar.

$
0
0

You can make an animation using progressing indicator in sapui5 app while doing some service calling.

 

Here is how you can make it. Hope this helps someone.

 

Br,

 

Dong Zhu

 

 

------------------ codes:

 

 

In "Controller" .js code:

 

   onInit: function() {

    tid=null;

   },

 

   some_evt handler func(){

       call the Start/Stop indicator funcs defined in Utility codes

   }

 

In "View" code:

 

           var oProgInd = new sap.ui.commons.ProgressIndicator("ProgInd", {

            width: "580px",

            showValue:false,

            visible: true,

            barColor: sap.ui.core.BarColor.POSITIVE

        });

 

 

In "Utility" codes:

 

function stopProgInd(){
if(tid != null){
     var oProgInd = sap.ui.getCore().byId("ProgInd");
     oProgInd.setVisible(false);
     clearTimeout(tid);
     tid=null;
}
}

 

function startProgInd(){
if(tid == null){
  var oProgInd = sap.ui.getCore().byId("ProgInd");
  oProgInd.setVisible(true);
 
  progressInd(0);
  function progressInd(al) {
   oProgInd.setPercentValue( parseInt(al) );
   al= (al==100)? 0: al+10;
   oProgInd.setDisplayValue( "Loading data, please wait... "); 
   tid = setTimeout( function() { progressInd(al); }, 80 );
  };
}
}

Viewing all 789 articles
Browse latest View live




Latest Images