Search code examples
javascriptarraysmodelsapui5treetable

Editing a object of a tree table


I have a question to a tree table from SAPUI5. Here is my JSFiddle: (https://jsfiddle.net/vazOrt/5L6e97wj/11/)

I have in the last node, objects of clothing. I want in the change-function of the inputfield, to change the propertie "change" to true. This is the object {"name": "Red T-shirt", "amount": 16.99, "currency": "USD", "size": "s", "change": false}

If the user change the size in the inputfield i want to be update the object {"name": "Red T-shirt", "amount": 16.99, "currency": "USD", "size": "s", "change": true}

But i dont find any solution to came from the tree table to the object from the model. Have someone a idea how i can update the property of the object?

Thank You


Solution

  • I found a way to update your changed object's actual change property in that nested array. Additionally because you have two way binding, simply the accessed data can be updated as below.

    So the working changeState function:

    changeState: function(e) {
          const view = this.getView();
          const model = view.getModel();
          const data = model.getData();
    
          const fieldName = e.mParameters.id;
          const elem = e.oSource.oParent.mAggregations.cells.find(function(f) {
            return f.sId === fieldName;
          });            
          const state = elem.oParent._oNodeState;
          const groups = state.groupID.split('/').filter(function(a) { return a !== '' });
          const path = groups[groups.length - 1];
          const fullPath = path.split('_');
    
          let stringPath = 'catalog.clothing';
    
          for (let i = 0; i < fullPath.length; i++) {
            stringPath += '[' + fullPath[i] + ']'
          }
    
          const targetObject = Object.byString(data, stringPath);
          targetObject.change = true;
    
          console.log('changed', data);
    }
    

    Additional function what you need to add to your code - for this the credit is going to this answer:

    Object.byString = function(o, s) {
        s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
        s = s.replace(/^\./, '');           // strip a leading dot
        var a = s.split('.');
        for (var i = 0, n = a.length; i < n; ++i) {
            var k = a[i];
            if (k in o) {
                o = o[k];
            } else {
                return;
            }
        }
        return o;
    }
    

    Please find the JSFiddle here: https://jsfiddle.net/Ln31qtor/

    I hope that helps!