5

SAP UI5 Drag and Drop functionality for Table item... - SAP Community

 2 months ago
source link: https://community.sap.com/t5/technology-blogs-by-members/sap-ui5-drag-and-drop-functionality-for-table-items/ba-p/13574936
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Hey, welcome to the blog. I work as a developer in one of the SAP Partner companies.

Drag & Drop functionality is an elegant way to improve UX and in this article we will learn about how to implement drag and drop for table items, I am using sap.m.Table as an example.

Scenario:

My requirement is to implement Drag and Drop functionality for table items.

If we are giving user an option to rearrange the items, traditionally we would do this by adding buttons that reposition the table items in it's binding array

BlogImg1-1.png

but imagine if we have more items let's say 20 items and if we want to move the last item to 4th or 5th position, then using the above method we would have to click around 15 times to move it to the 4th position. In scenarios like these Drag and Drop will be very convenient. we can easily drag and drop at the required position with in the table.

In the below example I'm dragging Product 7 and dropping it below Product 1.

BlogImg1-2.png
BlogImg1-3.png

Coding :

1.Create a Table (sap.m.Table) in your xml file with some 'id'.

//View.xml

<Table id="idProductsList" alternateRowColors="true"
        items="{path: 'mTestModel>/Data/List'}" width="70%" growing="true" growingThreshold="15" 
        mode="MultiSelect" growingScrollToLoad="true" sticky="ColumnHeaders,HeaderToolbar">
        <headerToolbar>
            <OverflowToolbar style="Clear">
                <Title text="Products"/>
                <ToolbarSpacer/>
                <SearchField width="25%" placeholder="Search" class="sapUiTinyMarginEnd" liveChange="onFilter"/>
                <Button icon="sap-icon://excel-attachment" press="onPressExportExcel" />
            </OverflowToolbar>
        </headerToolbar>
        <columns>
            <Column minScreenWidth="Tablet" demandPopin="true" hAlign="Begin">
                <Text text="Title"/>
            </Column>
        </columns>
        <items>
            <ColumnListItem type="Navigation" press="onNavToMatriceDetail">
                <cells>
                    <VBox>
                    <ObjectIdentifier title="{mTestModel>title}"/>
                    <HBox>
                        <Button class="sapUiTinyMarginEnd" text="Up" press="onSectionMappingUpPress"></Button>
                        <Button text="Down" press="onSectionMappingDownPress"></Button>
                    </HBox>
                </VBox>
                </cells>
            </ColumnListItem>
        </items>
    </Table>




2. In your controller attach Drag and Drop event. Then we just need to find the position(index) of the item that was dragged(start index) and drop position(end index). We can find the end index only if the control is a list item that is an element with the class 'sapMListTblRow' but we can drag the row from any point. so we traverse the parent(from dragged element to it's parent and so on) until we find an element with the above mentioned class.

once we have these two values we can simply update the array that is bound to the table.

//controller.js

fnEnableDragAndDropforTable: function () {
            var that = this;
            var oModel = this.getView().getModel('mTestModel');
            var oTable = this.getView().byId("idProductsList");
   
            // Register drag and drop events
            oTable.addEventDelegate({
               onAfterRendering: function () {
                  var $items = oTable.$().find(".sapMListTblRow");
                  $items.attr("draggable", "true");
   
                  $items.on("dragstart", function (event) {
                        //finding start index
                        var index = Array.from(event.target.parentElement.children).indexOf(event.target);

                        //storing the start index within event data
                        event.originalEvent.dataTransfer.setData("text", index);
                  });
   
                  $items.on("dragover", function (event) {
                     event.preventDefault();
                  });
   
                  $items.on("drop", function (event) {
                    event.preventDefault();
                    var data = event.originalEvent.dataTransfer.getData("text");
                    var target = event.target;
                    
                    //finding end index
                    var isTableRow = false;
                    while(!isTableRow){
                        if(target.className && target.className.includes("sapMListTblRow")){
                            isTableRow = true;
                        }else{
                            target = target.parentElement;
                            isTableRow = false;
                        }
                    }
                 
                    if (target && target.className && target.className.includes("sapMListTblRow") && data !== "") {
                       var fromIndex = parseInt(data);
                       //end index
                       var toIndex = Array.from(target.parentElement.children).indexOf(target);
                 
                       var aItems = oModel.getProperty("/Data/List");
                       var removedItem = aItems.splice(fromIndex, 1)[0];
                       aItems.splice(toIndex, 0, removedItem);
                 
                       oModel.setProperty("/Data/List", aItems);
                    }
                 });
               }
            });
        }


3. Call the function 'fnEnableDragAndDropforTable' in your onInit or onAfterRendering hooks. That's it Drag and Drop will be enabled and we can just Drag and Drop the items in a Table.

one sample is available in SAPUI5 SDK, where we can drag items from one table to another table. please refer Sample: Table - Drag and Drop

Conclusion :

With this blog, I want to convey how we can add Drag and Drop feature for the table items. If we have already implemented it then please share your ideas as well.

Please reply here if you have any queries.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK