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

UI5 Programming Examples

$
0
0

Hi All,

            

      I searched and saved UI5 examples In SCN for learning purpose. Some of them will helpful for you also. And In SCN some of the Questions are asked again and again. So I given all those links here,

 

SDK is the best place to learn UI5. All the UI5 things will available here.

For .js View Programming examples - SAPUI5 SDK - Demo Kit

For .xml View Programming examples - SAPUI5 Explored

 

Passing values from 1 view to another view(List View to Detail View)

Passing a Value Between two SAPUI5 Mobile App P... | SCN

 

Passing value from List to detail in UI5 mobile... | SCN

 

Tab in ui5(Pressing Tab will focus on input fields)

Navigate across sapui5 table using arrow key

 

jQuery autotab examples

 

jQuery Plugin For Auto Tab Form Fields - autotab | Free jQuery Plugins

 

F4 inside table row(F4 value help in Inside sap.m.table)

 

https://jsfiddle.net/indrajithpatel/va0y7j7r/18/

 

Table rows move up and down(Interchanging the table rows)

 

JS Bin - Collaborative JavaScript Debugging</title>  <link rel="alternate" type="application/jso…

 

Getting Table Column Values(To get all the values available in the particular row)

 

http://jsbin.com/tipokenuki/1/edit?html,js,console,output

 

Set firstColumnCount based on List(Pagination based on given input in sap.ui.table rows)

JS Bin - Collaborative JavaScript Debugging</title>  <link rel="alternate" type="application/jso…

 

Get selected table row values

 

JS Bin - Collaborative JavaScript Debugging

 

Import csv as table values

http://help.sap.com/businessobject/product_guides/vi01/en/webide_visExp_en.pdf

 

Add Values into Table(Given input is adding to table row)

JS Bin - Collaborative JavaScript Debugging

Table view more, view less with out using growth property(using button number of rows displayed)

JS Bin - Collaborative JavaScript Debugging


Search field will filter the data by given inputs

SAPUI5: How to filter data with 2 or more values - Stack Overflow

List Data Binding

JS Bin - Collaborative JavaScript Debugging</title> <link rel="alternate" type="application/jso…

 

Sap.ui.Table Binding

JS Bin - Collaborative JavaScript Debugging</title> <link rel="alternate" type="application/jso…

 

Custom Control

JS Bin - Collaborative JavaScript Debugging</title> <link rel="alternate" type="application/jso…

 

 

Regards,

Santhosh Gowda


Smart Table in UI5

$
0
0

Hi All,

                The Smart Table is the table Generated based on oData metadata.

So, explicitly creating rows and columns not required. It will creates the rows and columns based on oData metadata. If you want to do some customization it is allows to modify.

Reference –

Smart Table - UI Development Toolkit for HTML5 (SAPUI5) - SAP Library

 

SAPUI5 Explored

 

This is my Project Structure,

  1. Index.html,

<!DOCTYPEHTML>

<html>

      <head>

              <metahttp-equiv="X-UA-Compatible"content="IE=edge">

              <metahttp-equiv='Content-Type'content='text/html;charset=UTF-8'/>

              <script src="https://sapui5.netweaver.ondemand.com/resources/sap-ui-core.js"

                          id="sap-ui-bootstrap"

                          data-sap-ui-libs="sap.ui.commons,sap.m"

                            data-sap-ui-xx-bindingSyntax="complex"

                          data-sap-ui-theme="sap_bluecrystal"

                          data-sap-ui-resourceroots='{"smarttable": "./"}'

                          >

              </script>

                <script>

sap.ui.getCore().attachInit(function() {

              new sap.ui.core.ComponentContainer({

                        height : "100%",

                        name : "smarttable"

             

                }).placeAt("content");

            });

        </script>

      </head>

      <bodyclass="sapUiBody"role="application">

              <divid="content"></div>

      </body>

</html>

 

Component.js,

jQuery.sap.declare("smarttable.Component");

jQuery.sap.require("sap.ui.model.resource.ResourceModel"); 

sap.ui.core.UIComponent.extend("smarttable.Component", {

  init : function()

  {

sap.ui.core.UIComponent.prototype.init.apply(this, arguments);

      var mConfig = this.getMetadata().getConfig();

  },

createContent : function() {

 

    returnnew sap.m.App({id :"idApp",pages: [

sap.ui.view({id : "idsmarttable", viewName : "smarttable.smarttable.SmartTable", type : sap.ui.core.mvc.ViewType.XML, viewData : this }),

]});

},

 

})

 

SmartTable.view.xml,

<core:Viewxmlns:core="sap.ui.core"xmlns="sap.m"

      xmlns:smartFilterBar="sap.ui.comp.smartfilterbar"xmlns:smartTable="sap.ui.comp.smarttable"

      xmlns:html="http://www.w3.org/1999/xhtml"

      xmlns:app="http://schemas.sap.com/sapui5/extension/sap.ui.core.CustomData/1"

      controllerName="smarttable.smarttable.SmartTable"height="100%">

      <Pageid="page"title="SmartTable - Customer Line Items"

              enableScrolling="false">

              <content>

              <!--

              "TableList" is the EntitySet name to get the table values           

              -->

                    <smartTable:SmartTableentitySet="TableList"

                          smartFilterId="smartFilterBar"tableType="Table"useExportToExcel="true"

                          useVariantManagement="false"useTablePersonalisation="true"header="Line Items"

                          showRowCount="true"persistencyKey="SmartTableAnalytical_Explored"

                          enableAutoBinding="true"/>

              </content>

      </Page>

</core:View>

 

SmartTable.controller.js,

sap.ui.controller("smarttable.smarttable.SmartTable", {

      onInit: function() {

              var oModel, oView;

                  oModel = new sap.ui.model.odata.ODataModel("YOUR URL", true);

                  oModel.setCountSupported(false);

                  oView = this.getView();

                  oView.setModel(oModel);

      },

});

Output,

 

Smart Form and Smart Field in UI5

$
0
0

Hi All,

     The Smart Form is the Form Generated based on oData metadata.

So, The form is generated based on the metadata (Labels, text and drop down also will be generated).

In your metadata.xml,

For Input and Text fields, sap:updatable="true" then your text will be in editable mode after click on edit button else it will be in text view.

example,

<Property Name="Description" Type="Edm.String" Nullable="false"

          MaxLength="256" sap:label="Description" sap:creatable="false"

          sap:updatable="true" sap:sortable="false" />

 

For DropDown,sap:text="CategoryName" should be mapped with the key for getting drop down.

 

<Property Name="Category" Type="Edm.String" Nullable="false"

          MaxLength="3" sap:label="Category" sap:creatable="false"

          sap:updatable="true" sap:sortable="false" sap:text="CategoryName" />

<Property Name="CategoryName" Type="Edm.String" Nullable="false"

          MaxLength="3" sap:label="Category Description" sap:creatable="false"

          sap:updatable="true" sap:sortable="false" />

 

 

Reference –

Smart Form - UI Development Toolkit for HTML5 (SAPUI5) - SAP Library


SAPUI5 Explored


My Project Structure,

  1. Index.html,

<!DOCTYPEHTML>

<html>

       <head>

              <metahttp-equiv="X-UA-Compatible"content="IE=edge">

              <metahttp-equiv='Content-Type'content='text/html;charset=UTF-8'/>

              <scriptsrc="https://sapui5.netweaver.ondemand.com/resources/sap-ui-core.js"

                           id="sap-ui-bootstrap"

                           data-sap-ui-libs="sap.ui.commons,sap.m"

                             data-sap-ui-xx-bindingSyntax="complex"

                           data-sap-ui-theme="sap_bluecrystal"

                           data-sap-ui-resourceroots='{"smartform": "./"}'

                           >

              </script>

                <script>

sap.ui.getCore().attachInit(function() {

               new sap.ui.core.ComponentContainer({

height : "100%",

                        name : "smartform"

                

                }).placeAt("content");

            });

        </script>

       </head>

       <bodyclass="sapUiBody"role="application">

              <divid="content"></div>

       </body>

</html>

  1. Component.js,
  2. jQuery.sap.declare("smartform.Component");
  3. jQuery.sap.require("sap.ui.model.resource.ResourceModel"); 
  4. sap.ui.core.UIComponent.extend("smartform.Component", {

  init : function()

  {

sap.ui.core.UIComponent.prototype.init.apply(this, arguments);

      var mConfig = this.getMetadata().getConfig();

  },

createContent : function() {

  

     returnnew sap.m.App({id :"idApp",pages: [

sap.ui.view({id : "idsmartform", viewName : "smartform.smartform.smartform", type : sap.ui.core.mvc.ViewType.XML, viewData : this }),

]});

},

 

})

  1. Smartform.view.xml,

<core:Viewxmlns:core="sap.ui.core"xmlns="sap.m"

  xmlns:smartForm="sap.ui.comp.smartform"xmlns:smartField="sap.ui.comp.smartfield"

  xmlns:html="http://www.w3.org/1999/xhtml"

  xmlns:app="http://schemas.sap.com/sapui5/extension/sap.ui.core.CustomData/1"

  controllerName="smartform.smartform.smartform"class="sapUiSizeCompact">

  <Pageid="page"title="Product"enableScrolling="false">

    <content>

      <smartForm:SmartFormid="smartForm"

        editTogglable="true"title="{SoldToName}">

        <smartForm:Grouplabel="Customer">

          <smartForm:GroupElement>

            <smartField:SmartFieldvalue="{SalesDocument}"/>

          </smartForm:GroupElement>

          <smartForm:GroupElement>

            <smartField:SmartFieldvalue="{SoldToName}"/>

          </smartForm:GroupElement>

          <smartForm:GroupElement>

            <smartField:SmartFieldvalue="{Status}">

              <smartField:configuration>

                <smartField:ConfigurationcontrolType="dropDownList"

                  displayBehaviour="descriptionAndId"/>

              </smartField:configuration>

            </smartField:SmartField>

          </smartForm:GroupElement>

        </smartForm:Group>

         <smartForm:Grouplabel="Address">

          <smartForm:GroupElement>

            <smartField:SmartFieldvalue="{HouseNo}"/>

          </smartForm:GroupElement>

          <smartForm:GroupElement>

            <smartField:SmartFieldvalue="{District}"/>

          </smartForm:GroupElement>

        </smartForm:Group>

 

      </smartForm:SmartForm>

    </content>

  </Page>

</core:View>

  1. smartform.controller.js,
  2. sap.ui.controller("smartform.smartform.smartform", {

       onInit: function() {

           var sURL, oModel, oView;

           oModel = new sap.ui.model.odata.ODataModel("URL”,true);

           oModel.setCountSupported(false);

           oView = this.getView();

           oView.setModel(oModel);

           oView.bindElement("/CollectionName('295003114')");

         }

});

 

Output,

 

A Simple Example for animation in SAPUI5 Application

$
0
0

Hi All,

 

Today i am going to share that how we can use the standard jQuery libraries and methods for providing an animation look to our development.

Many times i have seen that users ask about how i can implement jQuery libraries or methods in SAPUI5 applications. Basically our SAPUI5 is itself a customized jQuery library and we can use all basic methods of jQuery in our application.

 

Here i am going to use two standard methods of jQuery for providing some animation look to my dialog. You can animate any of your UI elements using these standards methods.


In my scenario there is a dialog box which opens when a button is clicked.


Whenever we open a dialog in SAPUI5 application this opens in the center by default. In some cases we would like to animate our UI elements for providing the better feel and look to our application.


Just as usual i have created an application with sap.m library with one controller and a view.


This is the code in my index.html file.


<!DOCTYPEHTML>

<html>

       <head>

              <metahttp-equiv="X-UA-Compatible"content="IE=edge">

              <metahttp-equiv='Content-Type'content='text/html;charset=UTF-8'/>

 

              <scriptsrc="resources/sap-ui-core.js"

                           id="sap-ui-bootstrap"

                           data-sap-ui-libs="sap.m"

                           data-sap-ui-theme="sap_bluecrystal">

              </script>

              <!-- only load the mobile lib "sap.m" and the "sap_bluecrystal" theme -->

 

              <script>

                           sap.ui.localResources("slidingdialog");

                           var app = new sap.m.App({initialPage:"idview11"});

                           var page = sap.ui.view({id:"idview11", viewName:"slidingdialog.view1", type:sap.ui.core.mvc.ViewType.JS});

                           app.addPage(page);

                           app.placeAt("content");

              </script>

       </head>

       <bodyclass="sapUiBody"role="application">

              <divid="content"></div>

       </body>

</html>


I have just created a view and controller in eclipse.Now i am going to create a button in my view and when it will be pressed, this event will open a dialog having anmimation in which it will slide down from top to the centre location.

This is the content of my view.


       createContent : function(oController) {        

                         

              var oDialog = new sap.m.Dialog("loginmenu",{

                     title: "Hello",

                     afterOpen: function(){

                         oController.swingDown();                          // Implemented in controller                         

                     },

              });

 

              var oButton1 = new sap.m.Button({

                     text: "Press me",

                     press: function(){

                           oDialog.open();

                           oDialog.$().offset({top:"-100", left: "50%"});     // Initial position of Dialog out of frame using                                                                               // offset method of jQuery

                     }

              });

              returnnew sap.m.Page({

                     title: "Title",

                     content: [

                     oButton1

                     ]

              });

       }


Now this is the swingDown method in my controller.


sap.ui.controller("slidingdialog.view1", {

       swingDown: function() {

               $("#loginmenu").animate({top: "+=50%"}, 2000, "swing");

                  },              

});


This method will animate the dialog box.

From this location i have taken some help. jQuery Effects - Animation


This is very simple example for animation but if basic is clear then we may move forward for complicated one.


Thanks

Dhananjay Choubey

Session Expired

$
0
0

Session Expired


In Web Application development, many times we come across a situation where we need to check if our session is expired or not.


What is session expired?


Session_Expired is a server-side event, meaning it is triggered on the web server and has nothing to do with a request by the client.

1.       On each client request, check if a specific Session variable is set. If it is not, it means the previous Session has expired and the new Session must be populated.


2.       Have a javascript call on the client that periodically goes back to the server to check if the Session is still valid. If the Session has expired, you can warn the user that their Session is about to expire.


3.       On each client request, we can check if our session is valid or not.


In my demo I am going with third step where on each client request I am calling a method to check that if my session is still available or not.

I have a SAP Gateway response were we get a popup to enter our system username and password for validation.

1.png

SAP Gateway server asks to login again if we have crossed some time limit that means our session has been expired.

In many web based developments we force our users to login again to the website if they are victim of session expired event.

 

I have created a simple SAPUI5 application. This is the structure. For demo purpose I have created three html files for navigation. You can do it with views also.

 

2.PNG

 

Now this is the code in my Index.html.

<!DOCTYPEHTML>

<html>

       <head>

              <metahttp-equiv="X-UA-Compatible"content="IE=edge">

              <metahttp-equiv='Content-Type'content='text/html;charset=UTF-8'/>

           

 

              <scriptsrc="resources/sap-ui-core.js"

                           id="sap-ui-bootstrap"

                           data-sap-ui-libs="sap.ui.commons,sap.m"

                           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>

                           sap.ui.localResources("sessionexpired");

                           var view = sap.ui.view({id:"idview11", viewName:"sessionexpired.view1", type:sap.ui.core.mvc.ViewType.JS});

                           view.placeAt("content");                       

                        

              </script>

 

       </head>

       <bodyclass="sapUiBody"role="application">

              <divid="content"></div>

       </body>

</html>

Now this is the code in my Index2.html. Simply I have kept buttons in both index2.html and index3.html file.

<!DOCTYPEHTML>

<html>

       <head>

              <metahttp-equiv="X-UA-Compatible"content="IE=edge">

              <metahttp-equiv='Content-Type'content='text/html;charset=UTF-8'/>

           

 

              <scriptsrc="resources/sap-ui-core.js"

                           id="sap-ui-bootstrap"

                           data-sap-ui-libs="sap.ui.commons,sap.m"

                           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>

              var oButton = new sap.m.Button({

                     text: "Expired"

              });                 

                        

              oButton.placeAt("content");

              </script>

 

       </head>

       <bodyclass="sapUiBody"role="application">

              <divid="content"></div>

       </body>

</html>

Now this is the code in my Index3.html.

<!DOCTYPEHTML>

<html>

       <head>

              <metahttp-equiv="X-UA-Compatible"content="IE=edge">

              <metahttp-equiv='Content-Type'content='text/html;charset=UTF-8'/>

           

 

              <scriptsrc="resources/sap-ui-core.js"

                           id="sap-ui-bootstrap"

                           data-sap-ui-libs="sap.ui.commons,sap.m"

                           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>

              var oButton = new sap.m.Button({

                     text: "NOT EXPIRED"

              });                 

                        

              oButton.placeAt("content");

              </script>

 

       </head>

       <bodyclass="sapUiBody"role="application">

              <divid="content"></div>

       </body>

</html>

This is my view’s code.

  1. sap.ui.jsview("sessionexpired.view1", {

 

       /**SpecifiestheControllerbelongingtothisView.

       *Inthecasethatitisnotimplemented,orthat"null"isreturned,thisViewdoesnothaveaController.

       *@memberOfsessionexpired.view1

       */

       getControllerName : function() {

              return"sessionexpired.view1";

       },

 

       /**IsinitiallycalledonceaftertheControllerhasbeeninstantiated.ItistheplacewheretheUIisconstructed.

       *SincetheControllerisgiventothismethod,itseventhandlerscanbeattachedrightaway.

       *@memberOfsessionexpired.view1

       */

       createContent : function(oController) {

           

              var oButton = new sap.m.Button({

                     text: "Check Session Expired",

                     press: oController.checkForSession

              });

 

              return oButton;

       }

 

});

This is my controller’s code.

  1. sap.ui.controller("sessionexpired.view1", {

       checkForSession : function(){

var str="chksession=true";

jQuery.ajax({

                type: "GET",

                url: "proxy/http/HOST:PORT/sap/opu/odata/sap/ZDC_TEST_SRV/",

                data: str,

                cache: false,

                success: function(res){

                    if(res == "1") {

                    alert('Your session has been expired!');

                    window.location.replace("index2.html");

                    }else{

                    alert('Your session has not been expired!');

                    window.location.replace("index3.html");

                    }

                }

});

}

});

References:-

http://stackoverflow.com/questions/12502295/redirect-to-login-page-after-session-timeout

http://w3lessons.info/2014/01/01/how-to-check-expired-sessions-using-php-jquery-ajax/


I generally use simple codes for better understanding. You may always go with complicated ones.

 

Regards

Dhananjay

#SAPTechEd Lecture of the Week: SAPUI5 Overview and Code Best Practices - What You Need to Know (since TechEd)

$
0
0

Hi all,

 

in case you did not yet have the opportunity to or simply not yet decided to listen to the TechEd Session UXP201 from Las Vegas Oct 2014, you now have the opportunity to fix that watching the attached video. I briefly start to put SAPUI5 into the context of SAP UI Technologies, then you get an overview of SAPUI5 and afterwards the focus is set to implementation best practices. As many planned innovations seen from the perspective Oct. 2014 have already materialized, the section of code best practices has to be updated and extended. Please see the latest preview of the UI5 release 1.30 (being  1.29.1-Snapshot) on http://openui5.org/download.html respectively the news in http://openui5.tumblr.com/post/121579731137/first-preview-of-openui5-1-30.

 

 

So after having watched the video for the overview, please spend some time on the blog above and carefully study the extensive new UI5 tutorials and best practices. This will give you many assets/hints that you most likely missed so far.

 

Best regards

Stefan

SAPUI5 application in PHONEGAP to get salary structure in Mobile

$
0
0

Hi all,

 

I wrote code using openui5 kit version 1.28 which will display our salary structure when we give our CTC and BASIC as input

Attachment implementation in SAP UI5(CRM and SAP UI5 integration)

$
0
0

In this blog we will demonstrate how to send attachment from SAP UI5 front-end screen to back-end with ODATA.

 

I came across a requirement, where I have to design a custom FIORI like app. The app contains master and detail page, where master displays list of complaints from CRM and detail page contains the detail of selected complaint, detail includes, item and attachment and header data. The attachment should show in both CRM and well as SAP UI5, UI's.

       app.png

The solution shown below can be implemented in any CRM scenario where you require attachments (Attachment can be any type format).


ODATA Section:  As we knows that CRM attachment get stores in Content Server, so we need to read and write our attachment in content server. We are going to use cl_crm_documents class to achieve this functionality.

 

Below is the step you have to follow to achieve this functionality with ODATA.


1. Create a structure with attachment attribute.

     structure.PNG

2. Open transaction SEGW, and create entity with the above structure and generate the object.

     entity.PNG

3. Create another entity like in my case I have created complaint, see below screenshot, so totally there will be two entities.

     entity architecture.PNG

4. After that you have to select attachment entity type as media( click on Entity Type -> check media check box)

 

5.  To define mime type of attachment we need to redefine, define method of MPC_EXT class.

     

    

                          super->define( ).

                         data: lo_entity   type ref to /iwbep/if_mgw_odata_entity_typ,

                           lo_property type ref to /iwbep/if_mgw_odata_property.

                           lo_entity = model->get_entity_type( iv_entity_name = 'Complain_Attachments' ).

                          if lo_entity is bound.

                                lo_property = lo_entity->get_property( iv_property_name = 'MimeType' ).

                                lo_property->set_as_content_type( ).

                         endif.

6. After this we have to redefine create stream method of DPC_EXT class , which is the method to add attachment into the content server. See below code

   

(Please see attached file create_stream)

 

7. To read the attachment from content server we need to redefine the get_stream method of DPC_EXT class.

   

  (Please see attached file get_stream)

 


SAP UI5 Section: To implement the attachment functionality from front-end you have to follow below steps.

 

1. Write below code in XML vew.In XML view; if you are using IconTabFilter then paste this code inside it.  

 

<UploadCollection id="UploadCollection"

maximumFilenameLength="55" multiple="true" items="{/results}"

showSeparators="None" change="handleChange" fileDeleted="onFileDeleted"

fileRenamed="onFileRenamed" fileSizeExceed="onFileSizeExceed"

typeMissmatch="onTypeMissmatch" uploadComplete="onUploadComplete">

<UploadCollectionItem documentId="{Objid}" fileName="{Name}" mimeType="{MimeType}" thumbnailUrl="{thumbnailUrl}"

 

url="{                path: 'Objid',

                                                                                                                                     formatter:'crmpoc.formatter.Formatter.getURL'

                                                                                                                                                }"

enableDelete="true"  enableEdit="true"/>

</UploadCollection>

 

Note: you have to do some modification accordingly.

 

Here I am creating UploadCollection for uploading multiple documents in SAP backend

 

2. Now write below code in controller of the view.

   

     We have to implemented onChange event of UploadCollection, this method is responsible to send your attachment into backend, in this method we are doing following things.

 

  1. 1. Getting 'x-csrf-token' from ajax request.
  2. 2. Setting Upload URL to upload collection.
  3. 3. Setting header for the request by adding UploadCollectionParameter.

 

After this method you will be able to see your attachment in CRM.

 

(Please see attached file onchange)

 

3. To read an attachment we have to write a formatter function which will get URL of particular attachment when you will click on file name.

 

Write below code in Formatter.js

 

formatter.Formatter = {

     

       getURL: function(value){

//Return url which is based on your parameters, in our case it is complaint id and values.

               return"<Server URL>/<Service Name>/Complain_AttachmentsSet(Class='CRM_L_ORD',Objtype='L',ComplaintId='" + lComplainId + "',Objid='"+ value +"')/$value";

       }     

};


Please let me know if you are facing any issue in this code and also if you have any new idea reply on this.


Thanks,

JP


Simple SAPUI5 Application for addition of two numbers using SAP Web IDE

$
0
0

Hello Everyone,

 

I have come across questions about designing layouts and passing values between the layouts and what not, while working on SAPUI5 in SAP Web IDE.

I have also realized when I started using SAP Web IDE, that there isn't enough documentation to help you create a complete application. This blog might help beginners while designing simple SAPUI5 apps using both SAP Web IDE and Eclipse.

 

Prerequisites-

 

1. You should have SAP Web IDE configured on your System (or Eclipse Kepler/Luna with SAPUI5 ABAP Repository Team Provider add-on).

2. You should have a basic knowledge of MVC architecture, and Java script and HTML syntax (don't worry if you don't; your app will still work. You just won't understand how).

 

Let us begin in steps.

 

1. Create a project.

 

1. On the main screen of SAP Web IDE, go to File -> New -> Project from Template.

2. Select SAPUI5 Application Project from the template selection screen, and press NEXT.

3. Enter the name "AdditionProject" in the space provided, and press NEXT.

4. Fill in the details as shown below, and press NEXT, and then FINISH.


 

Project Namespace.PNG

2. Understanding the index.html file.


     Double-click on the index.html file in the left pane. The index file should open in your right pane of your SAP Web IDE screen.

We are going to refer to MVC architecture to build our application. This means that your index.html file will not contain your code for the layout and the logic.

Your index.html file will look something like this-

 

index.PNG

 

As you can see, the application uses sap.ui.commons library for coding and development. Your view view1 is placed at "content" at the div id="content" in the body. This is practically all the significance the index.html file has in a typical MVC adhering application. Your content will contain your view view1.js, which will contain your layout and the Controller, which will call your view1.controller.js, which will contain your logic. It is hard to comprehend in the beginning, but this document will be self-explanatory.

 

3. Building the View.

 

1. Open the folder 'VIEW'. It has the files view1.js and view1.controller.js. Double-click the file view1.js

2. the view1.js will have two methods-

          getControllerName : function() {

            return "view.Details";

          },

     and

          createContent : function(oController) {

 

          }

     We need to create our layout in the createContent method. Type the following lines of code in this method-

   

     createContent : function(oController) {

   

     var oLayout = new sap.ui.commons.layout.MatrixLayout({

          width : '100%',

          widths : ['5%', '20%', '40%', '15%']

       });

 

       var oLabel1 = new sap.ui.commons.Label({

          text : "Number1: "

       });

 

       var oTF1 = new sap.ui.commons.TextField({

          id : "Number1"

          });  

    

        var oLabel2 = new sap.ui.commons.Label({

          text : "Number2: "

       });

    

       var oTF2 = new sap.ui.commons.TextField({

          id : "Number2"

          });

        

       var oLabel3 = new sap.ui.commons.Label({

          text : "Result: "

       });

    

       var oTF3 = new sap.ui.commons.TextField({

          id : "Result"

          });

        

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

               text : 'Submit'

       });

       oButton.attachPress(oController.handleButtonClicked);

    

       oLayout.createRow(null, null, null, null);

       oLayout.createRow(null, oLabel1, oTF1, null);

       oLayout.createRow(null, oLabel2, oTF2, null);

       oLayout.createRow(null, oLabel3, oTF3, null);

       oLayout.createRow(null, null, oButton, null); 

 

       return oLayout;

    }

 

Let us see this code briefly.

1. We have used the sap.ui.commons library which has the properties layout, label, textField, button etc.

2. We have created a matrix layout in the view.

3. We then created 3 Labels and 3 corresponding TextFields to store Inputs and the result for our Addition app.

4. We then created a button to which we have attached the event attachPress, for which we pass the function handleButtonClicked through the Controller.

5.We then add everything to the layout as 4 rows as shown. This layout will be returned to our "view1.view" which will be returned to our div id="content" in the index.html.


4. Building the controller.


1. Double-click on the view1.controller.js file in the VIEW folder. It should open in the right pane of your screen.

2. You can see a lot of commented code in the file. Delete everything until your file contains only this-

          sap.ui.controller("view.View1", {


          });

3. Now, the only task at hand is to assign our addition logic to the attachPress event of our button. This will generate the addition of the numbers you type in         the textField oTF1 and oTF2, and display the result in the textField oTF3.

4. Type the following code in between the parenthesis-


          handleButtonClicked : function(){

          var oTF1 = sap.ui.getCore().getElementById("Number1").getValue();

          var oTF2 = sap.ui.getCore().getElementById("Number2").getValue();

          var oTF3 = sap.ui.getCore().getElementById("Result");

          oTF3.setValue(+oTF1 + +oTF2);

 

5. This is a fairly simple code where we fetch the pre-declared variables oTF1, oTF2, oTF3 and then set the result of addition to the variable oTF3.

 

5. Test the App.

 

Our app is completed and ready to run! Click on index.html in the left pane, and then press RUN. A new window will pop up where your app will be visible.

 

The final app, when you run it in a small layout, looks something like this-

final.PNG

 

Thank You for reading this.

 

Feel Free to contact me in case you have any doubts.

 

Regards,

-NK

Generate PDF at Client Side with jsPDF plugin - Part 1

$
0
0

Working with plugin jsPDF in SAPUI5 Application

 

  1. Generate PDF at Client Side with jsPDF plugin - Part 1
  2. Generate PDF at Client Side with jsPDF plugin - Part 2

 

1.      First we need to develop an application, in which we will display our data from backend system. Here in my demo I have taken a Simple Form with default values in input field.


     a. Create an SAPUI5 Application. This is my code.


INDEX.HTML


<!DOCTYPEHTML>

<html>

       <head>

              <metahttp-equiv="X-UA-Compatible"content="IE=edge">

              <metahttp-equiv='Content-Type'content='text/html;charset=UTF-8'/>

 

              <scriptsrc="resources/sap-ui-core.js"

                           id="sap-ui-bootstrap"

                           data-sap-ui-libs="sap.m,sap.ui.commons"

                           data-sap-ui-theme="sap_bluecrystal">

              </script>

              <!-- only load the mobile lib "sap.m" and the "sap_bluecrystal" theme -->

 

              <script>

               sap.ui.localResources("jspdffinaltest1");

                           var app = new sap.m.App({initialPage:"idview11"});

                           var page = sap.ui.view({id:"idview11", viewName:"jspdffinaltest1.view1", type:sap.ui.core.mvc.ViewType.JS});

                           app.addPage(page);

                           app.placeAt("content");

              </script>

 

       </head>

       <bodyclass="sapUiBody"role="application">

              <divid="content"></div>

       </body>

</html>


VIEW1.VIEW.JS (View Code)


sap.ui.jsview("jspdffinaltest1.view1", {

 

       /**SpecifiestheControllerbelongingtothisView.

       *Inthecasethatitisnotimplemented,orthat"null"isreturned,thisViewdoesnothaveaController.

       *@memberOfjspdffinaltest1.view1

       */

       getControllerName : function() {

              return"jspdffinaltest1.view1";

       },

 

       /**IsinitiallycalledonceaftertheControllerhasbeeninstantiated.ItistheplacewheretheUIisconstructed.

       *SincetheControllerisgiventothismethod,itseventhandlerscanbeattachedrightaway.

       *@memberOfjspdffinaltest1.view1

       */

       createContent : function(oController) {

          

              var oLayout = new sap.ui.layout.form.SimpleForm("formId",{

                 

                     title: "Employee Data",

                     content: [

                           

                               new sap.m.Label({text: "Employee ID"}),

                               new sap.ui.commons.TextView({

                                                text : 'DCHOUBEY',

                                                wrapping : false,

                                                width : '200px',

                                                semanticColor: sap.ui.commons.TextViewColor.Positive,

                                                design: sap.ui.commons.TextViewDesign.H3

                                                }),

                                 

 

                               new sap.m.Label({text: "Employee Name"}),

                               new sap.ui.commons.TextView({

                                                text : 'DHANANJAY CHOUBEY',

                                                wrapping : false,

                                                width : '250px',

                                                semanticColor: sap.ui.commons.TextViewColor.Positive,

                                                design: sap.ui.commons.TextViewDesign.H3

                                                }),

                           

 

                               new sap.m.Label({text: "Email ID"}),

                               new sap.ui.commons.TextView({

                                                text : 'DCHOUBEY@gmail.com',

                                                wrapping : false,

                                                width : '300px',

                                                semanticColor: sap.ui.commons.TextViewColor.Positive,

                                                design: sap.ui.commons.TextViewDesign.H3

                                                }),

 

                               new sap.m.Label({text: "Mobile Number"}),

                               new sap.ui.commons.TextView({

                                         text : '9876543210',

                                         wrapping : false,

                                         width : '300px',

                                         semanticColor: sap.ui.commons.TextViewColor.Positive,

                                         design: sap.ui.commons.TextViewDesign.H3

                                         }),

 

                               new sap.m.Label({text: "Website Link"}),

                               new sap.ui.commons.TextView({

                                         text : 'www.google.com',

                                         wrapping : false,

                                         width : '300px',

                                         semanticColor: sap.ui.commons.TextViewColor.Positive,

                                         design: sap.ui.commons.TextViewDesign.H3

                                         }),

                           

                               new sap.m.Label({text: ""}),

            ]

                 

              });

          

 

              var oButton =              new sap.m.Button("buttonId",{

                                                       text: "Download PDF",

                                                       width : '200px',

                                                       press: function() {

                                                              oController.display();

                                                       }

});

          

              returnnew sap.m.Page({

                     title: "Title",

                     content: [

                               oLayout, oButton

                     ]

              });

       }

 

});


VIEW1.CONTROLLER.JS (Controller Code, Right now of no use)


sap.ui.controller("jspdffinaltest1.view1", {

 

       display: function(){

          

       }

});


2.      Our application has been developed now and this is how it’s look like.


Output.PNG


3.      Now we need to print this simple form at frontend. For this we need to include libraries or say .js files to our index.html file.

          a. For this I visited this URL and downloaded the zipped folder. https://parall.ax/products/jspdf .

          b. Extracted it to my machine.

          c. After extracting the file, I found a file named with jspdf.js

          d. Now we need to include this file in our application. For that I wrote like this in my index.html file. <script src="jspdf.js"></script> and               copied jspdf.js file and pasted it to webContent folder of my project.

          e. Now we need to display our PDF. For that I wrote a simple code for displaying PDF in my display method of controller.

 

              vardoc = new jsPDF('p','pt','a4', true);

          

              //We'll make our own renderer to skip this editor

              var specialElementHandlers = {

                     '#buttonId': function(element, renderer){

                           returntrue;

                     }

              };

          

              doc.fromHTML($('#formId').html(),

                           60,

                           60,

                           {

                     'width': 750,

                     'elementHandlers': specialElementHandlers

              }

              );

          

                     doc.save('form.pdf');

                 

       }


4.      According to jsPDF plugin my code must work. I was happy that using this plugin is so easy and this will make our life simple. I executed my application.

Ohhh What is this? From here my frustration started.

 

error1.PNG

 

I Spent a lot of time for searching answer to this error and at last I found a solution to solve this.

I also need to include these three files to our index.html.


              <scriptsrc="jspdf.plugin.from_html.js"></script>

              <scriptsrc="jspdf.plugin.split_text_to_size.js"></script>

              <scriptsrc="jspdf.plugin.standard_fonts_metrics.js"></script>

 

Thanks to google. I found the solution.

But did I won? Not a chance. I just cleared the first step and second was waiting for me.

 

error2.PNG

 

To solve this error, I searched for an adler32cs.js file with same name and I found one here to this folder. jsPDF-0.9.0rc2\libs\Deflate.

 

But as I pasted it to my webContent folder. Again another was waiting for me. Till now it was clear that I have to add a file until I solve all of my errors. Added a file from the same folder with name deflate.js.

 

error3.PNG

 

But now when executed my code there was some another error. But anyway google is with us and I found this error here. http://stackoverflow.com/questions/20340194/doc-save-throwing-error-with-jspdf .

 

error4.PNG

 

This time I was taking extra precautions so altogether added this two files.

              <scriptsrc="FileSaver.js"></script>

              <scriptsrc="FileSaver.min.js"></script>

Found it at this location jsPDF-0.9.0rc2\libs\FileSaver.js.

 

5.      I executed my code after this long hectic search and implement techniques and WOW this time a pdf was downloaded. Without a second delay I clicked on that PDF and yes I got some data in PDF. Yes it was the same data which was in my form but this was not looking same as my form was.


result.PNG


I was disappointed but at the same moment there was some spark, that yes this is possible.


My eyes are bleeding red now. Doing research for the same and I will let you guys know in my second blog.

 

Thanks all for your patience. I need a break now.

 

 

Regards

Dhananjay

Web Components. The Future of Web Development?

$
0
0

The Theory

 

Let’s say, you want to develop a new web application. An important step in your technical conception is the choice of an UI - library. Beside SAPUI5, there are a vast number of great UI frameworks and technologies, so it’s quite complicated to keep an overview.

 

But almost all of these frameworks have conceptual insufficiencies, especially when you want to develop encapsulated, re-usable elements. Just have a look at a part of the HTML markup of the SAPUI5 ListBox control:

 

list_box_markup.png

 

As you can see, all single elements of the control are exposed. This behavior leads to the following problems:

 

  • Details of the implementation are leaking.
  • Global stylesheets can affect the look and feel of the control.
  • When you make a query for "ul" or "li" elements (e.g. document.querySelectorAll("li")), the mentioned markup is now part of the result.

 

Besides, the SAPUI5 ListBox is only re-usable within a SAPUI5 application. When you create an application with e.g. angular.js, it’s not possible to integrate a single control of the SAPUI5 library. Instead, you need to include at least the core framework to use its controls. The actual problem is, that nearly all UI - frameworks use different approaches for control development and implementation. They don’t use a common standard for components. And that means, they don’t work together.


This is where Web Components comes in. The following graphic illustrates the role of this new technology.


web_components.png


The layer „Web Components“ provides real encapsulated, re-usable building blocks. It’s the new basis for frameworks and applications.


The Practise


Enough theory! Let’s have a look at the code. Web Components consists of these four technologies (although each can be used separately):

 

  • HTML Imports
  • HTML Templates
  • Custom Elements
  • Shadow DOM

 

I’m going to show you in this post, how to create a simple Web Component. All what you need is a text editor, a Web Server and Google Chrome. At first, create a new HTML site with the following markup in your web servers root or project directory.

 

 

<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Web Components</title><style type="text/css">
a{
 color: #0f0f0f;
}</style></head><body><a href="#">Standard Link</a></body></html>

 

When you look at this site in your Chrome, you will see a simple link. Now, our goal is to develop a custom button element, which uses internally an "a" element. The result is attached at the post.

 

HTML Imports

 

HTML Imports are something like a packaging mechanism for Web Components. When you want to use a Web Component in your HTML-site, just import it! Create the HTML-File "custom-button.html" and refer to it from your index.html. Place this code at the end of your "head" section.


 

<link rel="import" href="custom-button.html">


We are going to implement the component-related markup and coding in our "custom-button.html".

 

HTML Templates

 

Of course, we want to render some HTML and Styles for our element. To do this, we place our markup and CSS into the new HTML template element. It’s important to know, that content in this tag will not be rendered when the page is loaded. The application itself needs to do this with some additional steps via JavaScript. Switch to the "custom-button.html" and add the following markup:

 

 

<template id="custom-button-template">  <style>  a{      display: inline-block;      border-radius: 2px;      padding: 10px 25px;      color: #fff;      background-color: #6083c2;      text-decoration: none;      transition: background-color .25s;  }  a:hover{  background-color: #345288;  }  </style>  <a></a></template>

 

Custom Elements

 

We also want to create our own custom HTML tags and elements. Besides, we need something like lifecycle callbacks, so we can execute coding in different states of the element. "Custom Elements" provides us these features. The following callbacks are currently available (see MDN):

 

  • createdCallback: The behavior you define occurs when the element is registered.
  • attachedCallback:The behavior occurs when the element is inserted into the DOM.
  • detachedCallback: The behavior occurs when the element is removed from the DOM.
  • attributeChangedCallback: The behavior occurs when an attribute of the element is added, changed, or removed

 

Let’s place a new custom element in our index.html (beneath the "a" element) and add some attributes:

 

 

<custom-button text="Click me!" href="#"></custom-button>

 

When you define a custom element, you must always use a hyphen in the name of the control! After that, we need a little bit JavaScript to describe our element and register it. In your "custom-button.html" paste the following coding beneath the "template" section.

 

 

<script type="text/javascript">
(function() {  // get a reference to the document element of the current script.  // we need this later in our example  var importDoc = document.currentScript.ownerDocument;  // create a prototype for the new element.
// basis is the common HTMLElement Interface  var CustomButtonProto = Object.create(HTMLElement.prototype);  // implement a lifecycle callback  CustomButtonProto.createdCallback = function(){       // todo  };  // registers the new custom element in the browser  document.registerElement("custom-button", {prototype: CustomButtonProto});  })();</script>

 

This is one possible approach for creating and registering a custom element. You can create the prototype of your new element in different ways. But i think, this one is pretty clear. Besides, it’s also possible to base a custom element on a native element like "a". In other words, you can inherit from native controls. Such an element has a different tag syntax and looks like this <a is="my-anchor">.

 

Shadow DOM

 

Shadow DOM is the key for encapsulation the JavaScript, CSS and templating in a Web Component. With this technology, we are able to separate our component specific code from the rest of the page. Let’s see, how it works. This is the implementation of our createdCallback method for the custom element.



CustomButtonProto.createdCallback = function(){  // select the template element
 var template = importDoc.querySelector("#custom-button-template");  // get the attributes of our custom element and transfer the values  // in our template   template.content.querySelector("a").innerHTML = this.getAttribute("text");  template.content.querySelector("a").href = this.getAttribute("href");  // create a copy of the templates content, so we can place it in the current document 
 var clone = document.importNode(template.content, true);  // insert the content to the existing element(this reference) via shadom dom 
 this.createShadowRoot().appendChild(clone);  }

 

Now we are done. When you open the index.html in your browser and inspect the markup of your custom element, you should see something like this:

shadow_dom.png

 

The section „#shadow-root“ proves, that the implementation of our control is encapsulated.

 

  • The internal style of the "a" element does not affect the "a" element in the index.html.
  • Changing the global style of "a" elements won’t affect out custom control.
  • Performing document.querySelectorAll("a") in your browser console won’t return the internal "a" element of your custom button.

 

Because our custom element is nothing more than an ordinary HTMLElement, we can treat it like a normal element. So you can add eventlisteners, query it etc.

 

It’s important to understand, that a Web Component can be „viewless“, so it just contains logic. This concept should be well known for all Web Dynpro developers (model/viewless WD-Components). The idea behind Web Components is the creation of elements for all kinds of use cases.

 

 

Conclusion

 

Good Bye SAPUI5, Hello Web Components? No, and there are several reasons for this.

 

  • The browser support is pretty poor right now, because Web Components only work in Google Chrome by default. Check out the support tables at caniuse for more information.
  • Of course you can use polyfills, which provide the required functionalities even in older browsers. Unfortunately, there are some problems, especially with Shadow DOM.
    • You need a lot of code.
    • Very bad performance with some browser.
    • Some functionality can’t be emulated (e.g. NodeList).
  • SAPUI5 is still a state-of-the-art framework and well integrated in the SAP ecosystem. If you want to develop a business application, which needs an integration to your existing SAP environment(Fiori), SAPUI5 should be your primary choice.

 

In my opinion, Web Components are going to play a major role in future web development. Currently, i recommend to just observe this technology. When the browser support gets better and more projects like Polymer exists, then it’s really time to start with Web Components.

 

Sources:

 

WebComponents.org - A place to discuss and evolve web component best-practices

Web Components - Mozilla Developer Network

Google I/O 2015 - Polymer and modern web APIs: In production at Google scale

Generate PDF at Client Side with jsPDF plugin - Part 2

$
0
0


  1. Generate PDF at Client Side with jsPDF plugin - Part 1
  2. Generate PDF at Client Side with jsPDF plugin - Part 2


In my previous blog we saw that how to display as a PDF, a simple form using jsPDF plugin at client side.

But in part 1 we were unable to download PDF as same as our Form. We were getting data row wise and this was not looking cool.


In this blog we will solve this problem. If you are unable to understand what I am talking about then go to part-1.

When I was searching on Google I found out this link. This gave me a hint that where I have to move. http://stackoverflow.com/questions/28193487/how-to-use-addhtml-function-in-jspdf

I downloaded the zipped file from this link.

After downloading this zipped folder extracted it to machine.

When I started copying this to my project, every single js file was throwing error. I don’t know what was this and again took help of google.

With too many tabs opened, I saw this link.

I saved this file as a local .js file to my system.

I thought that this is of no use to me but downloaded this also. I will tell you what benefit for downloading this was.

I copied html2canvas.js to webContent folder of my project.

And commented the code which was earlier written in method display() of controller with this code. I found it somewhere but I don’t remember from where.

              var doc = new jsPDF('p','pt','a4');

          

              doc.addHTML($('#formId').get(0),function() {

                  doc.save('form.pdf');

              });

But OMG!!.

Again an error.

 

error5.PNG

 

But I was sure that this is related to some .js file inclusion. But I was not sure that what was that but then the another file I have downloaded strike to my mind and I also included that file to my webContent folder. But again the error was same.


Then I commented all of these lines from my Index.html leaving behind that two javascript files.


<!--          <script src="jspdf.js"></script> -->

<!--          <script src="jspdf.plugin.from_html.js"></script> -->

<!--          <script src="jspdf.plugin.split_text_to_size.js"></script> -->

<!--          <script src="jspdf.plugin.standard_fonts_metrics.js"></script> -->

<!--          <script src="adler32cs.js"></script> -->

<!--          <script src="deflate.js"></script> -->

<!--          <script src="FileSaver.js"></script> -->

<!--          <script src="FileSaver.min.js"></script> -->


And this time when I pressed the button in my app, a PDF was downloaded. And this time PDF was same as my form. I checked it with table and it was also working for it.


Now I have commented a lot of scripts file and then checked if our previous code will execute or not and that was also working perfectly.

So after total of one day and half night spend I came to conclusion that we don’t need to include all of these files in my application.


<!--          <script src="jspdf.js"></script> -->

<!--          <script src="jspdf.plugin.from_html.js"></script> -->

<!--          <script src="jspdf.plugin.split_text_to_size.js"></script> -->

<!--          <script src="jspdf.plugin.standard_fonts_metrics.js"></script> -->

<!--          <script src="adler32cs.js"></script> -->

<!--          <script src="deflate.js"></script> -->

<!--          <script src="FileSaver.js"></script> -->

<!--          <script src="FileSaver.min.js"></script> -->


Only this single file was enough for our part-1 blog.


<script src="jspdf.debug.js"></script>

We can also include this as our .js files.


<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>

<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"></script>

 

This is the output.


output2.PNG

Table Display Below

output3.PNG


Anyway by this hard R&D I learned a lot and I am planning to research some more.If you also learned something then let me know by your valuable comments.


Next time I will come with SAP Gateway data and one another thing that is how to display this same PDF in our browser only without downloading.


Wish me good luck.

 

Note:- As i found somewhere that many of the elements of jQuery are not supported with jsFile then this will be also applicable for UI5 applications.

 

 

Regards

Dhananjay

Rename and Delete operation for attachment with SAP ODATA

$
0
0

I am writing this blog to continuation of my blog Attachment implementation in SAP UI5(CRM and SAP UI5 integration)

In my previous blog I have explained, how to create ODATA for attachment , I have explained create and read attachment operations for both front-end and back-end.

 

In this blog I am going to explain rename and delete operations for attachment, with the help of these operations you can able to rename and delete your attachment from sap ui5/fiori screen and also you will be able to delete the attachment.When you will perform these operation , they are going to reflect in CRM on premise as well.

 

Creation of ODATA will be same as I described in my previous blog Attachment implementation in SAP UI5(CRM and SAP UI5 integration, so I am directly explaining rename and delete operations.

 

ODATA creation for delete an attachment : (Please see entity creation in my previous blog)

 

Write below code in the method DELETE_ENTITY of DPC_EXT  class.

 

datals_key_tab type /iwbep/s_mgw_name_value_pair.

data :    ls_loio                type skwf_io,

           ls_loio1                type skwf_io,

           ls_delete_loio type skwf_io,

           ls_key type crmt_object_id,

           lv_cp_guid             type <crm guid type.,

           ls_object_id type swotobjid,

           ls_bor_object type sibflporb,

           lt_loios type table of skwf_io.

 

* Read key values

 

read table it_key_tab into ls_key_tab with key name = 'ComplaintId'.

if sy-subrc = 0.

   ls_key = ls_key_tab-value.

endif.

 

read table it_key_tab into ls_key_tab with key name = 'Objtype'.

if sy-subrc = 0.

   ls_loio-objtype = ls_key_tab-value.

  endif.

 

read table it_key_tab into ls_key_tab with key name = 'Class'.

if sy-subrc = 0.

   ls_loio-class = ls_key_tab-value.

  endif.

 

read table it_key_tab into ls_key_tab with key name = 'Objid'.

if sy-subrc = 0.

   ls_loio-objid = ls_key_tab-value.

  endif.

 

 

call function 'CRM_ORDERADM_H_GUID_GET_OW'

         exporting

           iv_object_id            = ls_key

         importing

           ev_orderadm_h_guid      = lv_cp_guid

         exceptions

           record_not_found        = 1

           object_id_is_not_unique = 2

           others                  = 3.

 

ls_object_id-objtype = 'BUS2000120'.

ls_object_id-objkey  = lv_cp_guid.

 

class cl_swf_utl_convert_por definition load.

ls_bor_object =

        cl_swf_utl_convert_por=>convert_bor_to_ibf( ls_object_id ).

 

append ls_loio to lt_loios.

 

   call method cl_crm_documents=>delete

     exporting

       business_object = ls_bor_object

       ios             = lt_loios.



ODATA creation for rename an attachment : (Please see entity creation in my previous blog)


Write below code in the method UPDATE_ENTITY of DPC_EXT  class.


data:

          ls_key_tab            type /iwbep/s_mgw_name_value_pair,

          es_entityset type zcl_zcomplaint_attachm_mpc=>ts_complain_attachments.

 

data :   ls_loio                type skwf_io,

           ls_loio1                type skwf_io,

           ls_key type crmt_object_id,

           lv_cp_guid             type <crm guid type>,

           lv_attach_name type skwf_descr,

           es_error type skwf_error.

 

* Read key values

 

read table it_key_tab into ls_key_tab with key name = 'ComplaintId'.

if sy-subrc = 0.

   ls_key = ls_key_tab-value.

endif.

 

read table it_key_tab into ls_key_tab with key name = 'Objtype'.

if sy-subrc = 0.

   ls_loio-objtype = ls_key_tab-value.

  endif.

 

read table it_key_tab into ls_key_tab with key name = 'Class'.

if sy-subrc = 0.

   ls_loio-class = ls_key_tab-value.

  endif.

 

read table it_key_tab into ls_key_tab with key name = 'Objid'.

if sy-subrc = 0.

   ls_loio-objid = ls_key_tab-value.

  endif.

 

 

call function 'CRM_ORDERADM_H_GUID_GET_OW'

         exporting

           iv_object_id            = ls_key

         importing

           ev_orderadm_h_guid      = lv_cp_guid

         exceptions

           record_not_found        = 1

           object_id_is_not_unique = 2

           others                  = 3.

 

* Read request data

     io_data_provider->read_entry_data( importing es_data = es_entityset ).

 

lv_attach_name    = es_entityset-file_name.

 

 

call method cl_crm_documents=>rename_object

   exporting

     is_io             = ls_loio

     iv_name           = lv_attach_name

   importing

     es_error          = es_error

 

endif.

Generate PDF at Client Side with jsPDF plugin - Part 3

$
0
0

1. Generate PDF at Client Side with jsPDF plugin - Part 1

2. Generate PDF at Client Side with jsPDF plugin - Part 2

 

As I promised I am back.

Many times we need to show our document as a table and sometimes we feel like it’s good to print our JSON data or OData from backend only means no need to display it on frontend side.


In my two previous blog I explained how to print data which is available on our frontend and by the ID of the elements we printed our PDF document. But I met a scenario where I wanted to print my table from the JSON Data.


Scenario was:-

1. What if my table data is too long and it is displayed wrapped on frontend side.

At that time my document which will be printed will not be complete or say we will see ….. at the end of our long text. So I didn’t met my requirement.


2. What if I don’t want to display my table at front end?


Now this was really a big problem. I continued my search on SDN as well as stackoverflow websites for relevant resources. This was the current thread which was live and discussion was going on.

http://scn.sap.com/thread/3757553

But this didn’t helped me as from beginning I knew that I have to use this file.

 

This is a lot of story.


Anyway, yes we need a different plugin for printing our backend data as table to PDF format i.e. AutoTable – Table plugin for jsPDF.

In earlier blog I told you that only this jspdf.debug.js file is enough and we don’t have to include a lot of source file to our index.html.

And another plugin is AutoTable plugin.


Download the zip folder and extract it. You will see this file jspdf.plugin.autotable.js

We just have to keep this two files in our index.html.



I have developed a simple application with a button on click of which will download a PDF.


So this is code in Index.HTML.

<!DOCTYPEHTML>

<html>

            <head>

                        <metahttp-equiv="X-UA-Compatible"content="IE=edge">

                        <metahttp-equiv='Content-Type'content='text/html;charset=UTF-8'/>

                     

 

                        <scriptsrc="resources/sap-ui-core.js"

                                                id="sap-ui-bootstrap"

                                                data-sap-ui-libs="sap.ui.commons"

                                                data-sap-ui-theme="sap_bluecrystal">

                        </script>

                     

                        <scriptsrc="jspdf.debug.js"></script>

                        <scriptsrc="jspdf.plugin.autotable.js"></script>

                     

                        <!-- add sap.ui.table,sap.ui.ux3 and/or other libraries to 'data-sap-ui-libs' if required -->

 

                        <script>

                                                sap.ui.localResources("jspdfautotable");

                                                var view = sap.ui.view({id:"idview11", viewName:"jspdfautotable.view1", type:sap.ui.core.mvc.ViewType.JS});

                                                view.placeAt("content");

                        </script>

 

            </head>

            <bodyclass="sapUiBody"role="application">

                        <divid="content"></div>

            </body>

</html>

 

Code of view.


            createContent : function(oController) {

                     

                        var oButton = new sap.ui.commons.Button("buttonId", {

                                    text: "Print Table.!!",

                                    press: oController.pressMe

                        })

 

                        return oButton;

            }


Code of Controller.


sap.ui.controller("jspdfautotable.view1", {

         

            pressMe: function(){

                     

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

                     

                        $.ajax({

                                    url: "http://services.odata.org/V3/Northwind/Northwind.svc/Customers?$format=json",

                                    dataType: "json",

                                    success: function(response){

 

                                                oModel.setData(response.value);

                                                var data = response.value;

                                                console.log(data);

                                             

                                                var columns = [

                                                               {title: "CustomerID", key: "CustomerID"},

                                                               {title: "CompanyName", key: "CompanyName"},

                                                               {title: "ContactName", key: "ContactName"},

                                                               {title: "ContactTitle", key: "ContactTitle"},

                                                               {title: "Address", key: "Address"},

                                                               {title: "City", key: "City"},

                                                               {title: "Region", key: "Region"},

                                                               {title: "PostalCode", key: "PostalCode"},

                                                               {title: "Country", key: "Country"},

                                                               {title: "Phone", key: "Phone"},

                                                               {title: "Fax", key: "Fax"}

                                                           ];

                                             

                                                var doc = new jsPDF('p', 'pt', 'a2');

                                                doc.autoTable(columns, data, {});

                                                doc.save('table.pdf');

                                    }

                        });

            }

});


We can also do it for the data which we are getting from SAP Gateway system.


This is final output.


table.PNG


You can also customize a lot of things. For that visit the official link of AutoTable.

This is last blog for jsPDF plugin but i will keep updating all of those three. I am working on how to display a letter at frontend from some backend data from gateway like invoice of a product purchased. I will update this same blog when i will find a proper solution.

 

Regards

Dhananjay

New SAPUI5 Walkthrough Tutorial

$
0
0

A new Walkthrough tutorial for learning SAPUI5 / OpenUI5 has just been released on the OpenUI5 beta demo kit and will be shipped officially to partners and customers with release 1.30 of SAPUI5 / OpenUI5. This first tutorial includes our latest best practices for building apps and shows many up-to-date features with small incremental steps. Once you have mastered the walkthrough - an anology from computer games - you know about all the important building blocks for creating marvelous apps.


With this new learning material we want to get developers kick-started for building apps with SAPUI5 / OpenUI5. This easy to consume and interactive learning material is suitable for beginners but also for more advanced developers that want to get an update on the latest features. Other topics that we will address in a similar format with tutorials soon are: Data Binding, Developing Apps, Testing Apps, Navigation & Routing, and more.

 

See for yourself:
Walkthrough Tutorial (Documentation in Developer Guide - 1.30 beta)
Walkthrough Tutorial (Code in Explored app - 1.30 beta)

The walkthrough tutorial consists of 35 small steps that start with a simple “Hello World” example and end with a fully responsive app by adding and explaining more and more features. You can just do the steps on your own for self-paced searning, or use them as material for workshops and trainings.

You will learn about the following topics as you go through the steps:

  • MVC Concepts
  • Structuring UI5 Apps
  • Components and App Descriptor
  • Layouting and CSS
  • Data Binding
  • Handling Mock Data
  • Unit Testing and Acceptance Testing
  • Navigation
  • Responsiveness

 

walkthrough_screenshot.jpg

Note:
The tutorials can be done in any IDE and server environment and thus do not contain any environment-specific descriptions. You can simply download the steps from the explored app (click on the code icon top-right) and run them on a local server with small adoptions like adjusting the ressource path. We will soon provide an overview section where the set up for SAP Web IDE and other typical development environments like grunt is described.

Have fun with this great new tutorial and let us know how you like it.

Thank you

Michael


Clear browser cache ( Chrome, Safari, IE ) from front-end Server to get updated version of SAPUI5 code

$
0
0


Step -1 Activate the Cache Buster

Activate SICF service /sap/bc/ui2/flp using transaction SICF.

 

SICF1.PNG

Step -2 Customize the Launchpad URL

Create External Aliases using transaction SICF->Choose External Aliases


SICF2.PNG

 

Enter external alias: /sap/bc/ui5_ui5/ui2/ushell/shells/abap and select /sap/bc/ui2/flp under tab Trg Element

 

SICF3.PNG

 

SICF4.PNG

 

Step -3 Upload your SAPUI5 code

Upload program: /UI5/UI5_REPOSITORY_LOAD

 

SICF6.PNG


 

Step -4 Calculate SAPUI5 application code

Select your SAPUI5 repository under based on single repository and execute

 

SICF7.PNG

Result

 

SICF9.PNG

 

Table /UI5/APPIDX contains all indexes of SAPUI5 repository

 

SICF10.PNG

 

 

Thanks.

 

Attachment delete and rename operation in SAP UI5

$
0
0


I am writing this blog to continuation of my blog Rename and Delete operation for attachment with SAP ODATA

In my previous blog I have explained, ODATA creation(backend part) for rename and delete operation,where I have implemented DELETE_ENTITY and UPDATE_ENTITY method of DPC_EXT class.


In this blog I am going to explain, how we will implement rename and delete operations for attachment in SAP UI5 (frontend logic)with uploadcollection control.Use blog Rename and Delete operation for attachment with SAP ODATA to implement ODATA logic.


Please follow my below blog for create and read odata Attachment implementation in SAP UI5(CRM and SAP UI5 integration and for delete and rename(odata backend part) Rename and Delete operation for attachment with SAP ODATA .


SAP UI5 code for rename attachment :


Please write below code in fileRenamed event of sap.m.UploadCollection .


onFileRenamed : function(oEvent){
jQuery.sap.require("sap.m.MessageToast");
var lComplainId =  gComplaintID;
var attachmentId = oEvent.mParameters.documentId;
var oEntry = {};

          oEntry.FileName = oEvent.mParameters.fileName;

      

        OData.request({

            requestUri : "<Server URL>/<ODATA proejct name>",

            method : "GET",

            headers : {           

"X-Requested-With" : "XMLHttpRequest",

                "Content-Type" : "application/atom+xml",

                "DataServiceVersion" : "2.0",

                "X-CSRF-Token" : "Fetch"

                 }

            },                    

            function(data, response) {

                 header_xcsrf_token = response.headers['x-csrf-token'];

                 oHeaders = {

                      "x-csrf-token" : header_xcsrf_token,

                      'Accept' : 'application/json',

                };

                          

            OData.request({

requestUri : "<Server URL>/<ODATA proejct name>/Complain_AttachmentsSet(Class='CRM_L_ORD',Objtype='L',ComplaintId='" + lComplainId + "',Objid='"+ attachmentId +"')",
method : "PUT",
headers : oHeaders,

                data : oEntry

               },                 

               function(data,request) {

                   loadAttachment(); // this is the funciton which loading the attachment in control

                 },        

               function(err) {

                      sap.m.MessageToast.show("Update failed due to following Exception : "+ err);

});

                 },

                          

            function(err) {

                  var request = err.request;

                  var response = err.response;

                  sap.m.MessageToast.show("Error in Get -- Request " + request + " Response " + response);

            });

}


SAP UI5 code for delete attachment :


Please write below code in fileDeleted event of sap.m.UploadCollection .


onFileDeleted : function(oEvent){
jQuery.sap.require("sap.m.MessageToast");
var lComplainId = gComplaintID;
var oEntry = {};

        oEntry.attachmentId = oEvent.mParameters.documentId;

        oEntry.complaintId = lComplainId;

        that = this;

        OData.request({

            requestUri : "<Server URL>/<ODATA proejct name>",

            method : "GET",

            headers : {

"X-Requested-With" : "XMLHttpRequest",

                "Content-Type" : "application/atom+xml",

                "DataServiceVersion" : "2.0",

                "X-CSRF-Token" : "Fetch"

                }

            },                      

            function(data, response) {

                header_xcsrf_token = response.headers['x-csrf-token'];

                oHeaders = {

                   "x-csrf-token" : header_xcsrf_token,

                   'Accept' : 'application/json',

                };

     

             OData.request({

requestUri : "<Server URL>/<ODATA proejct name>/Complain_AttachmentsSet(Class='CRM_L_ORD',Objtype='L',ComplaintId='" + oEntry.complaintId + "',Objid='"+ oEntry.attachmentId +"')",
method : "DELETE",
headers : oHeaders,

                 data : oEntry

                 },                 

                 function(data,request) {

loadAttachment();

              },        

              function(err){

sap.m.MessageToast.show("Couldn't Deleted due to following exception : "+ err);

              });

            },

                    

        function(err) {

                  var request = err.request;

                  var response = err.response;

                  sap.m.MessageToast.show("Error in Get -- Request " + request + " Response " + response);

        });
}

SAP Web IDE - How to use the Git Stash

$
0
0

Introduction

This post describes SAP Web IDE Git Stash feature.

If you are new to git functionality in Web IDE, please refer to How to Use the SAP Web IDE Git Client.

 

Stash Changes to Save Your Work

 

I have been working on part of my project, and I want to switch branches for a bit to work on something else.

I don’t want to commit half-done work and I want to get back to this point later.


All my changes appear in the staging table [1] .

Pay attention that at this stage the Show Stash button is disabled [2].

To stash my commit, I select Stash [3].

stash_01.jpg

A Stash dialog box appears, where I can add an optional message [4].

After pressing OK, the stash operation is completed . Now I can continue to work on something else.

stash_02.jpg

Pay attention that at this stage the Show Stash button is enabled [5] and the staging table is empty [6].

I finished working on the other things and now I am ready to get back to the changes I have stashed.

To see the stash list, I click on Show Stash [5].

stash_03.jpg

A Show Stash dialog box appears, where I can see my latest stash changes [7].

Now I can select to Apply, Pop or Drop my latest stash [8,9,10].

stash_04.jpg

To apply my stash, I select Apply [8].


Pay attention that at this stage the Show Stash button is enabled [11]. This means my files are still in the stash list available to apply, pop or drop.

Taking a look at the staging table shows that it contains the files I previously stashed  [12].

stash_05.jpg

OK, lets delete the stashed files from the stash list.

I'll click Show Stash button [11].

A Show Stash dialog box appears, where I can see my latest stash changes [7].

I'll select to Drop my latest stash [10].

Pay attention that at this stage the Show Stash button is disabled [2].


** Of course, Pop/Apply from the Stash List can lead to conflicts that you will have to resolve **


Thank You for reading this.

Feel free to contact me if you have any questions.

 

Regards,

Tomer

Analyzing JavaScript Remotely! With Vorlon.JS

$
0
0

Vorlon.JS

 

vorlon.png

 

An open source, extensible, platform-agnostic tool for remotely debugging and testing your JavaScript. Powered by node.js and socket.io.

 

That’s the official introducing. Sounds pretty interesting, right? I’ve tested Vorlon.JS with my current software project. The lesson is clear: Vorlon.JS provides useful features for analyzing and testing web based applications.

 

How does it work?

 

Vorlon.JS consists of a server-side and a client-side part. The Vorlon.JS server is based on node.js and provides a web fronted(dashboard) for inspecting connected applications. In your app, you enable Vorlon.JS by adding a script tag.  After that, the client will send various information to the server:

 

  • console logging
  • network activities (XHR and resource loading)
  • DOM tree and corresponding styles
  • all living JavaScript variables
  • a list of supported and unsupported browser features
  • local resources such as localStorage/cookies

 

All these information are very useful if you want to analyze remotely the status of an application. The following pictures illustrates an exemplary IT Infrastructure with Vorlon.JS.

 

architecture.png

 

Installation

 

Ensure, you have installed node.js. If not, visit the download section of the official website.

 

Open a console and type the following to install Vorlon.JS.

 

 

npm i -g vorlon

 

After that, you can start the server with:

 

 

vorlon

 

To connect e.g. a SAPUI5 application to the server, just add this script-tag in your index.html.

 

 

<script src="http://vorlonjs-server:1337/vorlon.js"></script>

 

Recommendation

 

For evaluation purposes, you can install Vorlon.JS on your local machine. For production, i recommend to install it on a separate server. If you have some experience with Amazon Web Services, it’s maybe a good idea to install Vorlon.js on a virtual server via EC2. Here’s a little instruction:

 

  • choose instance type t2.micro (that’s enough capacity for Vorlon.JS)
  • choose Amazon Linux AMI as OS
  • assign an elastic IP address to your instance, so you have a static reference to it
  • logon to your instance
  • install node.js
  • install Vorlon.JS

 

Using Cloud Computing has the major advantage, that you can stop the instance when you don’t need it. So you only pay for the resources you actually need. Besides, the provision of the Vorlon.JS server instance is done within minutes.

 

Working with Vorlon.JS

 

Dashboard and Plugins

 

When the server is running, the following exemplary URL starts the mentioned Vorlon.JS dashboard.

 

http://vorlonjs-server:1337/

 

Vorlon.JS plugins provide the actual debugging functionality. There are eight plugins by default, but you can also develop your own custom plugin. More information about the dashboard and the existing plugins can be found right here:

 

Vorlon.JS Dashboard

Vorlon.JS Plugins

 

Development/Production

 

Vorlon.JS works perfectly with SAPUI5 apps. In your development process, you can assign manually the mentioned script tag in your app. In production, i recommend to establish an URL parameter to enable Vorlon.JS. This approach is comparable with the „sap-config-mode=x“ parameter in Web Dynpro or FPM. If the respective parameter is assigned, you add the Vorlon.JS script tag in your index.html.

 

Hint: SAPUI5 provides a method for evaluating GET Parameter.

 

var value =  jQuery.sap.getUriParameters().get("myParam");

 

If you need to encrypt the communication between Vorlon.JS server and your app, just have a look at the documentation. The project has a great SSL support.

 

Conclusion

 

The idea behind Vorlon.JS is simply great! It’s definitely worth to check out the project!

 

Official Website

Github Project

Working With Multiple Branches with the Git Client

$
0
0

Introduction

One of the most powerful benefits of using Git is the support of multiple branches. In this blog post I’ll explain how to handle multiple branches with the SAP Web IDE Git client (create, remove, reset and rebase branches).

Note: For this blog post I assume that you are already familiar with the basic Git operations in the SAP Web IDE Git client and that you already have a Git repository in your workspace. If this is not the case, please read to How to Use the SAP Web IDE Git Client

A short terminology alignment before we start:

  • Check out – Updates the files in your workspace to match the selected branch.
  • Remote branch – Remote branches act as bookmarks to remind you where the branches in your remote repositories were the last time you connected to them.
  • Branching – A diversion from the main line of development so that work can continue without altering the main line.
  • Porting – The action of copying commits with code from one branch to another.

Create and Check Out a New Branch

The first thing you have to do when working with multiple branches is to create a local branch in your Git repository.

To do that, click the plus button in the Git pane [1]. In the dialog that opens, select the source branch [2] for the new local branch (the code in the new branch will be based on the source branch), provide a branch name [3], and click OK [4]. The new branch will be created and checked-out for you.

Currently, the SAP Web IDE Git client supports only one branch based on a remote branch, therefore, the Branch drop-down list does not contain the remote branch on which your local branch is based. (I will update this blog once this is available).

I choose to create a local branch based on the local master branch with the name newFeature.

1.png

On the newFeature branch I will create a new file called FileInNewBranch.js and commit it.

2.png

Now, when I check out the master branch (switch branch [5]) you can see that the FileInNewBranch.js file is not there [6].

3.png

This means that I have multiple versions of code on the same workspace. I can easily switch back to newFeature where I can add more content, creating a new commit, or amend my previous commit.

Rebase

There are several ways to port a change, I’ll describe here the rebase option and you can learn about the cherry-pick option in the Git History Pane blog post.

Let’s say that I have several commits on my newFeature branch and I want to port them to the master branch, so I’ll have the commits from the newFeature branch on the master branch. I check out the master branch (by selecting it from the Branch drop-down list [7]) and click Rebase [8]. In the Rebase dialog I select the newFeature branch [9] and click OK [10]. Now all my commits from the newFeature branch are ported to the master branch.

4.png

As you can see, my local master branch contains 2 commits [11] that the remote branch (origin/master) does not. (These are commits I ported from the newFeature branch.) You can also see that the 2 new files [12] I created on the newFeature branch are also on my master branch.

5.png

If you don’t need the created branch any more you can easily remove it by pressing the minus button [13]. Make sure that you really want to delete the local branch. This operation will remove the copy version (and all additions made to it) from the repository and it cannot be undone.


Reset

Let’s say you’ve performed one or more commits and now you want to reset the status of your local branch to what it was before the commits. Click the Reset button [14]. In the dialog that opens, select the branch whose status you want your branch to be reset to. Before clicking OK, select a reset type.

Reset mixed will keep your changes in the workspace (even if they come from multiple commits) and reset your commit’s status.

Reset hard will reset the commit status and will reset (remove) all the changes in your workspace. You cannot undo this operation, make sure that you really want to remove your changes/commits before using this operation.

In this example I mixed [15] the master branch to the origin/master [16] branch.

6.png

I have the FileInNewBranch.js file and the FileInNewBranchForCommitB.js file in my staging table [17] (uncommitted changes) and my local branch has the same status as the remote branch.

7.png

It is also possible to reset your branch against some other branch (not the one that your branch is based on), but this is an uncommon use case.

This blog post has shown you how to work with multiple branches and perform the following operations:

  • Create Branch
  • Rebase
  • Reset
  • Check Out
  • Remove Branch

  In the Git History Pane blog post I describe how to use the Git History pane and the cherry-pick option.

Viewing all 789 articles
Browse latest View live




Latest Images