简体   繁体   中英

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:

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;

}

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:

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)

The above snippet is from the chrome debugger. 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.

Thanks in advance Below I attach a screen shot of the index.html when ran in the browser along with my file structure. 在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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