Friday, 20 July 2018

How to create a custom control in UI5

Hi, Here is a simple and complete tutorial for writing custom control in SAP/Open UI5. Follow these simple steps to get start with all the steps are detailed with proper explanations wherever necessary.
  1. Create a new SAP UI5 Application Project in eclipse. (Make sure you have installed required tools for eclipse).
  2. Create a .js file for the custom control. Here sampleControl.js and paste the below code.
sap.ui.core.Control.extend("sampleControl",{
         metadata: {
properties: {
content: {
type: "object"
},
noOfyears: {
type: "int"
},
},
aggregations: {
leftArrow: {
type: "sap.ui.core.Icon",
multiple: false
},
rightArrow: {
type: "sap.ui.core.Icon",
multiple: false
}
},
events: {
eventPress: {
enablePreventDefault: true
}
}
},
init: function() 
{
jQuery.sap.require("sap.ui.core.IconPool");
        var leftArrow = new sap.ui.core.Icon({
src: sap.ui.core.IconPool.getIconURI("arrow-down"),
tooltip: "Scroll Left"
});
this.setAggregation("leftArrow", leftArrow);

var rightArrow = new sap.ui.core.Icon({
src: sap.ui.core.IconPool.getIconURI("arrow-down"),
tooltip: "Scroll Right"
});
this.setAggregation("rightArrow", rightArrow);
},
renderer: function(oRm, oControl) {
oRm.write("<div");
oRm.writeControlData(oControl);
oRm.writeClasses();
oRm.write(">");

oRm.write("<div class='rightArrow' align='center'><a href='#' id='left-button'></div>");
oRm.write("<div class='leftArrow' align='center'><a href='#' id='right-button'></div>");
oRm.write("</div>");    // closing parent most control div
},
onAfterRendering: function(oControl) {
         this._leftArrow.placeAt("left-button");
 this._rightArrow.placeAt("right-button");
}

Now our custom control which is having left and right arrows are ready to use. The key things to learn on this are : 
  1. Metadata : This is the data/properties that are set when instantiating the custom control from outside Ex: new sap.m.Input({text : "ABC"}). Here text is the metadata same way in our control content and no of years are the properties.
  2. Aggregations : This indicates that which are the controls that will be used inside our custom control. i.e. the type of relationship between our custom control and the other controls inside the custom control. Here if the association is maintained in place of aggregation then the life-cycle of the controls present inside the custom control will differ that of aggregations.
  3. Events: These are nothing but events which can be raised by our custom control. Ex : press event in sap.m.Input. Here if we just do this.fireEvent("event-name",value); then our custom control will raise that event along with the data to be sent
  4. All the new object creations should be done at the init() only since it will be called only once in the life-cycle, else more than one aggregation elements will be generated on the screen.

No comments:

Post a Comment