简体   繁体   English

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

[英]How to delete data from the model and database on button click in SAPUI5?

资料夹结构

Hi am trying to delete a single row from the database and model on button click. 您好,我尝试从数据库中删除一行并在单击按钮时进行建模。 In attached picture you can see my file structure. 在附图中,您可以看到我的文件结构。

mymodel.hdbdd: 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: 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: 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: 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: 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;

}

I am totally new to sapui5 and tried everything I could find online, but I get the error when retrieving the selected value just before I call ExcelQuery.xsjs: 我对sapui5完全陌生,并尝试了所有可以在网上找到的内容,但是在调用ExcelQuery.xsjs之前检索所选值时出现错误:

http://server-address/I313766_Hubert/perslist/services/ExcelQuery.xsjs?cmd=DeleteRequest&idrequest=undefined Failed to load resource: the server responded with a status of 500 (Internal Server Error) sap-ui-core.js:27 GET http://server-address/I313766_Hubert/perslist/services/ExcelQuery.xsjs?cmd=DeleteRequest&idrequest=undefined 500 (Internal Server Error) http://server-address/I313766_Hubert/perslist/services/ExcelQuery.xsjs?cmd = DeleteRequest&idrequest = undefined加载资源失败:服务器响应状态为500(内部服务器错误)sap-ui-core.js:27 GET http://服务器地址/I313766_Hubert/perslist/services/ExcelQuery.xsjs?cmd=DeleteRequest&idrequest=undefined 500(内部服务器错误)

The above snippet is from the chrome debugger. 上面的代码片段来自chrome调试器。 Could you please kindly help? 您能帮忙吗? I did some debugging myself and found out that the value selected from the table seems to be undefined, unless I refer to it the wrong way. 我自己进行了一些调试,发现从表中选择的值似乎是未定义的,除非我以错误的方式引用它。 I spent about four days trying to fix it by now, also tried all of the tuts I could find online - none of them work because either I can't retrieve the model or the value to be deleted. 到目前为止,我花了大约四天的时间来修复它,还尝试了所有可以在网上找到的tut,但是这些都不起作用,因为我无法检索模型或要删除的值。

Thanks in advance Below I attach a screen shot of the index.html when ran in the browser along with my file structure. 在此先感谢您在下面附上在浏览器中运行时index.html的屏幕截图以及我的文件结构。 在此处输入图片说明

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM