如何在SAPUI5中单击按钮时从模型和数据库中删除数据?

时间:2015-07-28 08:56:32

标签: javascript jquery model-view-controller sapui5

Folder structure

您正在尝试从按钮单击中删除数据库中的单行和模型。在附图中,您可以看到我的文件结构。

mymodel.hdbdd:

namespace I313766_Hubert.perslist.data;
@Schema: 'i313766_perslist'
context mymodel {
 type SString: String(60);
 @Catalog.tableType: #COLUMN
 Entity person {
 key ID: String(10); // element modifier 'key' defines that ID is primary key
 FIRSTNAME: SString;
 LASTNAME: SString;
 };

  context procedures{
 type pers {
 ID: String(10);
 FIRSTNAME: SString;
 LASTNAME: SString;
 };
 type errors {
 HTTP_STATUS_CODE : Integer;
 ERROR_MESSAGE : String(100);
 DETAIL : String(100);
 };
 };
};

perslist.controller.js:

sap.ui.controller("views.perslist", {
    onInit: function() {
        var sOrigin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ":" + window.location.port : "");
        var persListOdataServiceUrl = sOrigin + "/I313766_Hubert/perslist/services/pers.xsodata";
        var odataModel = new sap.ui.model.odata.ODataModel(persListOdataServiceUrl);
        this.getView().setModel(odataModel);
    },
    addNewPerson: function() {
        var firstName = this.getView().getFirstNameField().getValue();
        var lastName = this.getView().getLastNameField().getValue();
        var persons = {};
        persons.ID = "1";
        persons.FIRSTNAME = firstName;
        persons.LASTNAME = lastName;
        this.getView().getModel()
            .create("/Persons", persons, null, this.successMsg, this.errorMsg);
    },
    successMsg: function() {
        sap.ui.commons.MessageBox.alert("Person entity has been successfully created");
    },
    errorMsg: function() {
        sap.ui.commons.MessageBox.alert("Error occured when creating person entity");
    },
    onAfterRendering: function() {
        this.getView().getFirstNameField().focus();
    },
    deletePerson: function() {
             var oTable = sap.ui.getCore().byId("persTable");
             var data = oTable.getModel();
            // var removeModel = new sap.ui.model.odata.ODataModel("../services/requestCreate.xsodata/", true);
            if(data === null)
            {
                sap.ui.commons.MessageBox.show("Model value empty!","ERROR","ERROR");
            }
             var RowId = data.getProperty("firstNameFieldId",oTable.getContextByIndex(oTable.getSelectedIndex()));
             sap.ui.commons.MessageBox.show(RowId,"ERROR","ERROR");
             var aUrl2 = '../../services/ExcelQuery.xsjs?cmd=DeleteRequest'+'&idrequest='+escape(RowId)+''; 
                    // var aUrl2 = '../../../services/poWorklistQuery.xsjs?cmd=getTotalOrders'+'&groupby='+escape(groupBy)+'&currency=USD&filterterms=';
                        jQuery.ajax({
                           url: aUrl2,
                           method: 'GET',
                           dataType: 'json',
                           success: function ()
                           {
                               sap.ui.commons.MessageBox.show("Finally it worked","SUCCESS","SUCCESS");
                           },
                           error: function ()
                           {
                               sap.ui.commons.MessageBox.show("NOPE NOPE NOPE","ERROR","ERROR");
                           }
                        });

    }
});

perslist.view.js:

sap.ui.jsview("views.perslist", {
 oFirstNameField : null,
 oLastNameField : null,
 getControllerName : function() {
return "views.perslist";
 },
 createContent : function(oController) { // Create an instance of the table control
var oTable = new sap.ui.table.Table({ title : "Persons List", visibleRowCount : 6,
 firstVisibleRow : 3, selectionMode : sap.ui.table.SelectionMode.Single, id: "persTable" });
// add TableToolbar
var oTableToolbar = new sap.ui.commons.Toolbar();
// add first name field
var oFirstNameLabel = new sap.ui.commons.Label({ text : 'First Name' });
this.oFirstNameField = new sap.ui.commons.TextField({ id : 'firstNameFieldId', value : '',
 width : '10em' });
 oFirstNameLabel.setLabelFor(this.oFirstNameField);
 oTableToolbar.addItem(oFirstNameLabel);
 oTableToolbar.addItem(this.oFirstNameField);
// add last name field
var oLastNameLabel = new sap.ui.commons.Label({ text : 'Last Name' });
this.oLastNameField = new sap.ui.commons.TextField({ id : 'lastNameFieldId', value : '',
 width : '10em' });
 oLastNameLabel.setLabelFor(this.oLastNameField);
 oTableToolbar.addItem(oLastNameLabel);
 oTableToolbar.addItem(this.oLastNameField);
// add button
var oAddPersonButton = new sap.ui.commons.Button({ id : 'addPersonButtonId',
 text : "Add Person", press : function() {
 oController.addNewPerson();
 } });

 var oDelPersonButton = new sap.ui.commons.Button({ id : 'delPersonButtonId',
 text : "Delete person", press : function() {
oController.deletePerson();
 } });
 oTableToolbar.addItem(oAddPersonButton);
 oTableToolbar.addItem(oDelPersonButton);
 oTable.setToolbar(oTableToolbar);
// define the columns and the control templates to be used
 oTable.addColumn(new sap.ui.table.Column({
 label : new sap.ui.commons.Label({ text : "First Name" }),
 template : new sap.ui.commons.TextView().bindProperty("text", "FIRSTNAME"),
 sortProperty : "FIRSTNAME", filterProperty : "FIRSTNAME", width : "100px" }));
 oTable.addColumn(new sap.ui.table.Column({
 label : new sap.ui.commons.Label({ text : "Last Name" }),
 template : new sap.ui.commons.TextView().bindProperty("text", "LASTNAME"),
 sortProperty : "LASTNAME", filterProperty : "LASTNAME", width : "200px" }));
// bind table rows to /Persons based on the model defined in the init method of the
// controller (aggregation binding)
 oTable.bindRows("/Persons");
return oTable;
 },
 getFirstNameField : function() {
return this.oFirstNameField;
 },
 getLastNameField : function() {
return this.oLastNameField;
 }
});

的index.html:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>SAP HANA Platform E2E Dev Scenario: SAP HANA native
 PersonsList application</title>
<script src="/sap/ui5/1/resources/sap-ui-core.js" id="sap-ui-bootstrap"
data-sap-ui-libs="sap.ui.commons, sap.ui.table,sap.ui.ux3"
data-sap-ui-theme="sap_goldreflection">
</script>
<script>
 sap.ui.localResources("views");
var oAppHeader = new sap.ui.commons.ApplicationHeader("appHeader");
 oAppHeader.setLogoSrc("http://www.sap.com/global/images/SAPLogo.gif");
 oAppHeader.setLogoText("PersonsList application in SAP HANA XS");
 oAppHeader.setDisplayWelcome(false);
 oAppHeader.setDisplayLogoff(false);
 oAppHeader.placeAt("header");
var view = sap.ui.view({ id : "perslist-id", viewName : "views.perslist",
 type : sap.ui.core.mvc.ViewType.JS });
 view.placeAt("content");
</script>
</head>
<body class="sapUiBody" role="application">
 <div id="header"></div>
 <div id="content"></div>
</body>
</html>

ExcelQuery.xsjs:

function DeleteRequest() {
    var body = '';

    try {

        var IDRequest = $.request.parameters.get('idrequest');

        var query = 'Delete from \"I313766_Hubert.perslist.data::mymodel\" where \"Firstname\" = \''+ IDRequest +'\' ';

        //var query2 = 'Delete from \"IOREQUEST"."lucas.Exercise_UI.data::DaysUsed\" where \"IDRequest\" = \''+ IDRequest +'\' ';

        //select * FROM "IOREQUEST"."lucas.Exercise_UI.data::DaysUsed" where "IDRequest" like '%I033828%'

        $.trace.debug(query);
        var conn = $.db.getConnection();
        var pstmt = conn.prepareStatement(query);
        //var pstmt2 = conn.prepareStatement(query2);
        pstmt.execute();
        //pstmt2.execute();
        conn.commit();
        conn.close();




    } catch (e) {
        $.response.status = $.net.http.INTERNAL_SERVER_ERROR;
        $.response.setBody(e.message);
        return;
    }

    $.response.setBody(body);
    //$.response.contentType = 'application/vnd.ms-excel; charset=utf-16le';
    $.response.contentType = 'application/vnd.ms-excel; charset=utf-8';
    $.response.headers.set('Content-Disposition',
            'attachment; filename=Excel.txt');
    $.response.headers.set('access-control-allow-origin', '*');
    $.response.status = $.net.http.OK;

}

我是sapui5的新手,并尝试了我在网上找到的所有内容,但在调用ExcelQuery.xsjs之前检索所选值时出现错误:

http://server-address/I313766_Hubert/perslist/services/ExcelQuery.xsjs?cmd=DeleteRequest&idrequest=undefined无法加载资源:服务器响应状态为500(内部服务器错误) sap-ui-core.js:27 GET http://server-address/I313766_Hubert/perslist/services/ExcelQuery.xsjs?cmd=DeleteRequest&idrequest=undefined 500(内部服务器错误)

以上代码段来自chrome调试器。请你帮忙吗?我自己做了一些调试,发现从表中选择的值似乎是未定义的,除非我以错误的方式引用它。我花了大约四天时间尝试修复它,也尝试了我可以在网上找到的所有内容 - 它们都不起作用,因为我无法检索模型或要删除的值。

提前致谢 下面我在浏览器中添加了index.html的屏幕截图以及我的文件结构。enter image description here

1 个答案:

答案 0 :(得分:0)

In the event handler for the Delete button , you can try the following code

var oTable = sap.ui.getCore().byId("TableID");
var oRow = oTable.getRows()[oTable.getSelectedIndex()]
var rowValue = oTable.getModel().getProperty(oRow.getBindingContext().sPath);