OData demo 2

1 , 目錄

webapp
  |____index.html
  |____Component.js
  |____manifest.json
  |____controller
  |      |________App.controller.js
  |____model
  |      |________metadata.xml
  |      |________models.js
  |____view
         |________App.view.xml


2 , code

index.html

<!DOCTYPE HTML>
<html>
	<head>
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>Fiori Demo</title>
		<script id="sap-ui-bootstrap"
			src="../../resources/sap-ui-core.js"
			data-sap-ui-libs="sap.m,sap.ui.table"
			data-sap-ui-theme="sap_belize" 
			data-sap-ui-compatVersion="edge"
			data-sap-ui-resourceroots='{"ZFIORI": ""}'>
		</script>
		<script>
		///SE38>>UI5/UI5_REPOSITORY_LOAD  (上傳/下載 應用程序) //sap_belize //sap_bluecrystal
		//data-sap-ui-resourceroots='{"ZFIORI": "","sap.ui.demo.mock": "mockdata"}'
			sap.ui.getCore().attachInit(function() {
				new sap.m.App ({
					pages: [
						new sap.m.Page({
							title: "Fiori Demo", 
							enableScrolling : false,
							content: [ new sap.ui.core.ComponentContainer({
								height : "100%",
								name : "ZFIORI"
							})]
						})
					]
				}).placeAt("content");
			});
		</script>
	</head>
	<body class="sapUiBody sapUShellFullHeight" role="application">
	<div id="content" class="sapUShellFullHeight"></div>
	</body>
</html>

2 , Component.js

sap.ui.define(['sap/ui/core/UIComponent'],
	function(UIComponent) {
	"use strict";

	var Component = UIComponent.extend("ZFIORI.Component", {
		metadata : {
			manifest: "json"
		}
	});
	return Component;
});

3,App.view.xml

<mvc:View controllerName="ZFIORI.controller.App" 
	xmlns="sap.ui.table"
	xmlns:mvc="sap.ui.core.mvc"
	xmlns:u="sap.ui.unified"
	xmlns:c="sap.ui.core"
	xmlns:m="sap.m">
	<m:Page showHeader="false"
			enableScrolling="false"
			class="sapUiContentPadding" showNavBar="false" showNavButton="false" navButtonPress="onBack">
				<m:content>
                <!-- <Table noDataText="No data" id="idTable" fixedColumnCount="1"  selectionMode="MultiToggle"
                            items="{path:'/ZCDS_DEMO01Set',parameters:{select:'Fld1'},filters:[{path:'Fld1', operator:'NE', value1:''}]}">-->
                    <Table noDataText="No data" id="idTable" rows="{path:'/ZCDS_DEMO01Set'}"  visibleRowCount="20"
                           selectionMode="Single"  selectionBehavior="Row" enableGrouping="true">
					<toolbar>
					<m:Toolbar>
						<m:Title id="title" text="{i18n>DOCUMENT_ITEMS}"></m:Title>
						<m:ToolbarSpacer/>
						<m:ToggleButton icon="sap-icon://group-2" tooltip="{i18n>GROUP_BY}" press="callGroupDialog"/>
						<m:ToggleButton icon="sap-icon://sort"    tooltip="{i18n>SORT_BY}"  press="callSortDialog"/>
						<m:ToggleButton icon="sap-icon://excel-attachment" tooltip="{i18n>DOWN}" press="callDown"/>
						<m:ToolbarSeparator/>
						<m:Button icon="sap-icon://decline"  tooltip="{i18n>CLEAR}" press="clearAllFilters"/>
						<m:SearchField placeholder="Filter" search="handleSearch" width="15rem"/>
					</m:Toolbar>
					</toolbar>
                    <columns>
                        <Column id="Lfld1" sortProperty="Fld1" filterProperty="Fld1" width="20%">
                           <m:Text text="{i18n>KEY}" tooltip="{i18n>KEY}"/>
                           	<template>
								<m:Text text="{Fld1}"/>
							</template>
                        </Column>
                        <Column id="Lfld2" width="60%">
                            <m:Text text="{i18n>FLD2}" tooltip="{i18n>FLD2}"/>
                           	<template>
								<m:Text text="{Fld2}"/>
							</template>
                        </Column>
                        <Column id="Lfld3" width="20%">
                            <m:Text text="{i18n>FLD3}" tooltip="{i18n>FLD3}"/>
                           	<template>
							<m:ObjectStatus text="{
								path:'Fld3',
								type: 'sap.ui.model.type.Integer'}"
							state="{
								path: 'Fld3',
								formatter: '.formatAvailableToObjectState'
							}" />
							</template>
                        </Column>
                    </columns>
                     <footer>
						<m:Toolbar>
							<m:ToolbarSpacer/>
							<m:Button icon="sap-icon://create" tooltip="{i18n>NEW}" press="onCreate"/>
							<m:Button icon="sap-icon://edit"   tooltip="{i18n>CHG}" press="onUpdate"/>
							<m:Button icon="sap-icon://delete" tooltip="{i18n>DEL}" press="onDelete"/>
						</m:Toolbar>
					</footer>
              </Table>
		</m:content>
	</m:Page>
</mvc:View>

4 , App.controller.js

sap.ui.define([
	"sap/ui/core/mvc/Controller"
], function(Controller) {
	"use strict";
	var oModel;
	var sCurrentPath;
	var sCurrentDat;
	//var fnPress;
	return Controller.extend("ZFIORI.controller.App", {
		idTable:null,
		oResourceBundle: null,
		oGroupSort: {sGroupKey: null, bGroupDescending: null, sSortKey: null, bSortDescending: null}, 
		
		/**
		 * Initialization
		 */
        onInit: function() {
            oModel = this.getOwnerComponent().getModel();
            oModel.setUseBatch(false);
            this.getView().setModel(oModel);
            this.idTable = this.getView().byId("idTable");
            this.fnPress = this.handleActionPress.bind(this);
            //this.setTemp();
            //this.oResourceBundle = this.oApplicationFacade.getResourceBundle();
        },
		/**
		* Called when pressing nav back button
		*/
		onBack: function() {
			window.history.go(-1);
		},
		/**
		 * clear filter / sort
		 */
		 clearAllFilters: function() {
			this.idTable.getBinding("rows").filter(null, "Application");
			this.idTable.getBinding("rows").sort(null);
 
			var aColumns = this.idTable.getColumns();
			for (var i=0; i<aColumns.length; i++) {
				this.idTable.filter(aColumns[i], null);
				aColumns[i].setSorted(false);
			}
		 },
		/**
		 * Called if sorting button is pressed
		 */
		 persistGroupSortCustomization: function() {
			var oPersId = {
				container: "ZFIORI",
				item: "tableGroupSort"
			};
			var oPersonalizer = sap.ushell.Container.getService("Personalization").getPersonalizer(oPersId);
			oPersonalizer.setPersData({
				sGroupKey: this.oGroupSort.sGroupKey,
				bGroupDescending: this.oGroupSort.bGroupDescending,
				sSortKey: this.oGroupSort.sSortKey,
				bSortDescending: this.oGroupSort.bSortDescending
			});
		},
		callSortDialog : function() {
			if (!this._lineItemViewDialog) {
				this._lineItemViewDialog = new sap.m.ViewSettingsDialog({
					sortDescending: this.oGroupSort.bSortDescending,
					sortItems : [
						new sap.m.ViewSettingsItem({
							text : "Field1",
							key : "Fld1",
							selected: this.oGroupSort.sSortKey === "Fld1"
						}),
						new sap.m.ViewSettingsItem({
							text : "Field2",
							key : "Fld2",
							selected: this.oGroupSort.sSortKey === "Fld2"
						}),
						new sap.m.ViewSettingsItem({
							text :"Field3",
							key : "Fld3",
							selected: this.oGroupSort.sSortKey === "Fld3"
						})
					],
					confirm : jQuery.proxy(
						function(evt) {
							var oParams = evt.getParameters();
							this.oGroupSort.sSortKey = oParams.sortItem.getKey();
							this.oGroupSort.bSortDescending = oParams.sortDescending;
							this._groupSortItemTable();
							//this.persistGroupSortCustomization();
							this.iCurNumItems = 0;
						}, this)
				});
				jQuery.sap.syncStyleClass("sapUiSizeCompact", this.getView(), this._lineItemViewDialog);
			}
			this._lineItemViewDialog.open();
		},
		/* Called if sorting or grouping of table is changed */
		_groupSortItemTable : function() {
			var aSorter = [];
			if ((this.oGroupSort.sGroupKey !== null) && (this.oGroupSort.sGroupKey !== "")){
				aSorter.push(new sap.ui.model.Sorter(this.oGroupSort.sGroupKey, this.oGroupSort.bGroupDescending, true));
			}
			if ((this.oGroupSort.sSortKey !== null) && (this.oGroupSort.sSortKey !== "")){
				aSorter.push(new sap.ui.model.Sorter(this.oGroupSort.sSortKey, this.oGroupSort.bSortDescending, false));
			}
			this.idTable.getBinding("rows").sort(aSorter);
		},
		/**
		 * Called if grouping button is pressed
		 */
		callGroupDialog : function() {
			if (!this._groupSettingsDialog) {
				this._groupSettingsDialog = new sap.m.ViewSettingsDialog({
					groupDescending: this.oGroupSort.bGroupDescending,
					groupItems : [
						new sap.m.ViewSettingsItem({
							text : "Field1",
							key : "Fld1",
							selected: this.oGroupSort.sGroupKey === "Fld1"
						}),
						new sap.m.ViewSettingsItem({
							text : "Field2",
							key : "Fld2",
							selected: this.oGroupSort.sGroupKey === "Fld2"
						}),
						new sap.m.ViewSettingsItem({
							text :"Field3",
							key :"Fld3",
							selected: this.oGroupSort.sGroupKey === "Fld3"
						})
					],
					confirm : jQuery.proxy(
						function(evt) {
							var oParams = evt.getParameters();
							if(oParams.groupItem === undefined) {
								this.oGroupSort.sGroupKey = null;
								this.oGroupSort.bGroupDescending = null;
							} else {
								this.oGroupSort.sGroupKey = oParams.groupItem.getKey();
								this.oGroupSort.bGroupDescending = oParams.groupDescending;
							}
							this._groupSortItemTable();
							//this.persistGroupSortCustomization();
							this.iCurNumItems = 0;
						}, this)
				});
				jQuery.sap.syncStyleClass("sapUiSizeCompact", this.getView(), this._groupSettingsDialog);
			}
			this._groupSettingsDialog.open();
		},
		onPersoButtonPressed : function(){
			sap.m.MessageToast.show("in development...");
		},
		/**
		 * search
		 **/
		handleSearch:function(oEvent){
                var filters = [];
                var query = oEvent.getParameter("query");
                if (query && query.length > 0) {
                var filter = new sap.ui.model.Filter("Fld2", sap.ui.model.FilterOperator.Contains, query);
                filters.push(filter);
                }
                this.idTable.getBinding("rows").filter(filters);	
		},
		/**
		 * Get path
		 */
    	getDownloadUrl : function(oBinding, sFormat, aExclude) {
			var aParams = [],
	        sPath;
	        if (sFormat) {
	            aParams.push("$format=" + encodeURIComponent(sFormat));
	        }
	        if (oBinding.sSortParams) {
	            aParams.push(oBinding.sSortParams);
	        }
	        if (oBinding.sFilterParams) {
	            aParams.push(oBinding.sFilterParams);
	        }
	        if (oBinding.sCustomParams) {
	        	var sCustomParams = oBinding.sCustomParams;
	        	if (aExclude) {
		        	var aCustomParams = sCustomParams.split("=");
		        	if (aCustomParams.length === 2) {
		        		var sCustomParamsTmp = decodeURIComponent(aCustomParams[1]);
		
			        	for (var i = 0; i < aExclude.length; i++) {
			        		sCustomParamsTmp = sCustomParamsTmp.replace(aExclude[i] + ",", ""); //String + Comma
			        		sCustomParamsTmp = sCustomParamsTmp.replace(aExclude[i], ""); //String
			        	}
			
			        	sCustomParamsTmp = encodeURIComponent(sCustomParamsTmp);
			        	sCustomParams = aCustomParams[0] + "=" + sCustomParamsTmp;
		        	}
	        	}
	            aParams.push(sCustomParams);
	        }
	        
	        sPath = oBinding.oModel.resolve(oBinding.sPath, oBinding.oContext);
	        
	        if (sPath) {
	            return oBinding.oModel._createRequestUrl(sPath, null, aParams);
	        }
    	},
    	/**
    	 * download
        */
       callDown:function() {
			var t=this.byId("idTable");
			var b=t.getBinding("rows");
			var d=this.getDownloadUrl(b,"xlsx");
			sap.m.URLHelper.redirect(d,true);
       },
		/**
		* Show detial
		*/
        openDialog: function() {
            var oView = this.getView();

            // Open dialog
            var oEmpDialog = oView.byId("Detial");
            if (!oEmpDialog) {
                oEmpDialog = sap.ui.xmlfragment(oView.getId(),"ZFIORI.view.Dialog");
                oView.addDependent(oEmpDialog);
            }

            oEmpDialog.open();

            // Attach press event for CancelButton
            var oCancelButton = oView.byId("CancelButton");
            oCancelButton.attachPress(function() {
                oEmpDialog.close();
            });
        },
        /**
         * format - state
         */
        formatAvailableToObjectState : function (bAvailable) {
			return bAvailable > 100 ? "Success" : "Error"; //Warning,None   ==ObjectStatus[class,text,state,icon]
		},
        /**
         * run sap.ui.core.js Version: 1.11.2 ==> https://sapui5.hana.ondemand.com/resources/sap-ui-core.js
         */
		setTemp : function () {
			var oTable = this.getView().byId("idTable");
			
			var oTemplate = oTable.getRowActionTemplate();
			if (oTemplate) {
				oTemplate.destroy();
				oTemplate = null;
			}
			
			oTemplate = new sap.ui.table.RowAction({items: [
				new sap.ui.table.RowActionItem([{
				icon: "sap-icon://line-chart",
				type: sap.ui.table.RowActionType.Navigation,
				press: this.fnPress,
				visible: "true"
				}]
			)]});
			var iCount = 1;
			
			this.idTable.setRowActionTemplate(oTemplate);
			this.idTable.setRowActionCount(iCount);
		},
		/**
		 * fnPress event
		 */
		handleActionPress : function(oEvent) {
			var oRow = oEvent.getParameter("row");
			//var oItem = oEvent.getParameter("item");
			window.console.log(oRow.getBindingContext());
			//MessageToast.show("Item " + (oItem.getText() || oItem.getType()) + " pressed for product with id " +
			//	this.getView().getModel().getProperty("ProductId", oRow.getBindingContext()));
		},
		/**
		 * Table row selected
		 */
		getContextByIndex: function () {
			var selMode = this.idTable.getSelectionMode();
			var oContext = null;
			if(selMode === sap.ui.table.SelectionMode.MultiToggle) {
				var sels = [];
				sels = this.idTable.getSelectedIndices();
				for(var i=0;i<sels.length;i++) {
					oContext = this.idTable.getContextByIndex(sels[i]);
					window.console.log(oContext.getProperty("Fld1"));
				}
			}
			else { //Single
				var iIndex = this.idTable.getSelectedIndex();
				if (iIndex >= 0) {
					oContext = this.idTable.getContextByIndex(iIndex);
					sCurrentPath = oContext.getPath();
	            	sCurrentDat  = oContext.getProperty("Fld1");
				}
				else { // None
					sCurrentPath = null;
					sCurrentDat  = null;
				}
			}
		},
		/**
		 * select item
		 */
		onItemPress: function(oEvent) {
            var oContext = oEvent.getSource().getBindingContext();
            sCurrentPath = oContext.getPath();
            sCurrentDat  = oContext.getProperty("Fld1");
		},
		onrowChange: function(oEvent) {
			window.console.log(oEvent.getParameter("row"));
		},
		/**
		* Clear item
		*/
		onClearItem:function(obj){
            obj.byId("Key").setValue("");
            obj.byId("Fld2").setValue("");
            obj.byId("Fld3").setValue("");	
		},
		
		/**
		 * Create
		 */
		onCreate: function() {
			/* --demo
			var newData = {
				"d": {
					"Mandt": "800",
					"Fld1": "4",
					"Fld2": "Bruce Lee",
					"Fld3": 4
				}
			};

			oModel.create("/ZCDS_DEMO01Set", newData, {
				success: function(oData, oResponse) {
					window.console.log(oResponse);
				},
				error: function(oError) {
					window.console.log("Error", oError);
				}
			});
			*/
            var oView = this.getView();

            this.openDialog();
            var oEmployeeDialog = oView.byId("Detial");
            oEmployeeDialog.setTitle("Create Data");
            oView.byId("Key").setEditable(true);
            oView.byId("SaveEdit").setVisible(false);
            oView.byId("SaveCreate").setVisible(true);

            // clear
            this.onClearItem(oView);

            // commit save
            oView.byId("SaveCreate").attachPress(function() {
                var oNewEntry = {
                    // "Mandt": "800",
                    "Fld1": "",
                    "Fld2": "",
                    "Fld3": 0
                };

                // populate value from form
                oNewEntry.Fld1 = oView.byId("Key").getValue();
                oNewEntry.Fld2 = oView.byId("Fld2").getValue();
                oNewEntry.Fld3 = parseInt(oView.byId("Fld3").getValue());

                // Commit creation operation
                oModel.create("/ZCDS_DEMO01Set", oNewEntry, {
                    success: function() {
                        sap.m.MessageToast.show("Created successfully.");
                    },
                    error: function(oError) {
                    	sap.m.MessageToast.show("Error occurs.");
                        window.console.log("Error", oError);
                    }
                });

                // close dialog
                if (oEmployeeDialog) {
                    oEmployeeDialog.close();
                }
            });	
		},
		
		/**
		* Update data
		*/
		onUpdate: function() {
			/* --demo
			var newData = {
				"d": {
					"Mandt": "800",
					"Fld1": "4",
					"Fld2": "Hello world 44444",
					"Fld3": 4
				}
			};

			oModel.update("/ZCDS_DEMO01Set(Mandt='800',Fld1='4')", newData, {
				success: function(oData, oResponse) {
					window.console.log(oResponse);
				},
				error: function(oError) {
					window.console.log("Error", oError);
				}
			});
			*/
			this.getContextByIndex();
            // no employee was selected
            if (!sCurrentDat) {
                sap.m.MessageToast.show("No Item was selected.");
                return;
            }
            
			var oView = this.getView();

            this.openDialog();
            var oEmployeeDialog = oView.byId("Detial");
            oEmployeeDialog.setTitle("Edit Detial");
            oView.byId("Key").setEditable(false);
            oView.byId("SaveEdit").setVisible(true);
            oView.byId("SaveCreate").setVisible(false);

            // populate fields
            oView.byId("Key").setValue(oModel.getProperty(sCurrentPath + "/Fld1"));
            oView.byId("Fld2").setValue(oModel.getProperty(sCurrentPath + "/Fld2"));
            oView.byId("Fld3").setValue(oModel.getProperty(sCurrentPath + "/Fld3"));

            // Attach save event
            oView.byId("SaveEdit").attachPress(function() {
                var oChanges = {
                    "Mandt": "800",
                    "Fld2": "",
                    "Fld3": ""
                };
                // populate value from form
                oChanges.Fld2 = oView.byId("Fld2").getValue();
                oChanges.Fld3 = parseInt(oView.byId("Fld3").getValue());

                // commit creation
                oModel.update(sCurrentPath, oChanges, {
                    success: function() {
                        sap.m.MessageToast.show("Changes were saved successfully.");
                    },
                    error: function(oError) {
                    	sap.m.MessageToast.show("Error occurs.");
                        window.console.log("Error", oError);
                    }
                });

                // close dialog
                if (oEmployeeDialog) {
                    oEmployeeDialog.close();
                }
            });
		},
		
		/**
		* Delete employee
		*/
		onDelete: function(){
			/* --demo
			oModel.remove("/ZCDS_DEMO01Set(Mandt='800',Fld1='4')",{
				success: function(oData, oResponse) {
					sap.m.MessageToast.show("Deletion successful.");
					window.console.log(oResponse);
				},
				error: function(oError) {
					window.console.log("Error", oError);
				}
			});
			*/
			var that = this;
			this.getContextByIndex();
            // no line was selected
            if (!sCurrentDat) {
                sap.m.MessageToast.show("No Item was selected.");
                return;
            }

            var oDeleteDialog = new sap.m.Dialog();
            oDeleteDialog.setTitle("Deletion");

            var oText = new sap.m.Label({
                text: "Are you sure to delete item [" + sCurrentDat + "]?"
            });
            oDeleteDialog.addContent(oText);

            oDeleteDialog.addButton(
                new sap.m.Button({
                    text: "Confirm",
                    press: function() {
                        that.deleteItem();
                        oDeleteDialog.close();
                    }
                }));
                
                oDeleteDialog.addButton(
                new sap.m.Button({
                    text: "Cancel",
                    press: function() {
                        oDeleteDialog.close();
                    }
                }));

			oDeleteDialog.open();
		},
        // deletion operation
        deleteItem: function() {
            oModel.remove(sCurrentPath, {
                success: function() {
                    sap.m.MessageToast.show("Deletion successful.");
                },
                error: function(oError) {
                	sap.m.MessageToast.show("Error occurs.");
                    window.console.log("Error", oError);
                }
            });
        }
	});
});

5 , metadata.xml

<edmx:Edmx
    xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx"
    xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"
    xmlns:sap="http://www.sap.com/Protocols/SAPData" Version="1.0">
    <edmx:DataServices m:DataServiceVersion="2.0">
        <Schema
            xmlns="http://schemas.microsoft.com/ado/2008/09/edm" Namespace="ZFIORI_SRV" xml:lang="zh" sap:schema-version="1">
            <EntityType Name="ZCDS_DEMO01" sap:content-version="1">
                <Key>
                    <PropertyRef Name="Mandt"/>
                    <PropertyRef Name="Fld1"/>
                    <PropertyRef Name="Fld2"/>
                    <PropertyRef Name="Fld3"/>
                </Key>
                <Property Name="Mandt" Type="Edm.String" Nullable="false" MaxLength="3" sap:label="集團" sap:creatable="false" sap:updatable="false" sap:sortable="false" sap:filterable="false"/>
                <Property Name="Fld1" Type="Edm.String" Nullable="false" MaxLength="10" sap:label="Key" sap:creatable="false" sap:updatable="false" sap:sortable="false" sap:filterable="false"/>
                <Property Name="Fld2" Type="Edm.String" Nullable="false" MaxLength="20" sap:label="CharValue" sap:creatable="false" sap:updatable="false" sap:sortable="false" sap:filterable="false"/>
                <Property Name="Fld3" Type="Edm.Int32" Nullable="false" sap:label="IntValue" sap:creatable="false" sap:updatable="false" sap:sortable="false" sap:filterable="false"/>
            </EntityType>
            <EntityContainer Name="ZFIORI_SRV_Entities" m:IsDefaultEntityContainer="true" sap:supported-formats="atom json xlsx">
                <EntitySet Name="ZCDS_DEMO01Set" EntityType="ZFIORI_SRV.ZCDS_DEMO01" sap:creatable="false" sap:updatable="false" sap:deletable="false" sap:pageable="false" sap:content-version="1"/>
            </EntityContainer>
            <atom:link
                xmlns:atom="http://www.w3.org/2005/Atom" rel="self" href="./sap/ZFIORI_SRV/$metadata"/>
                <atom:link
                    xmlns:atom="http://www.w3.org/2005/Atom" rel="latest-version" href="./sap/ZFIORI_SRV/$metadata"/>
                </Schema>
            </edmx:DataServices>
        </edmx:Edmx>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章