0

I have a Tree element with MultiSelect mode, which looks good with checkboxes in every tree item. I wanted to make it so if I select one item, all of its children get selected as well. I have the tree in the view:

 <Tree selectionChange="onPress" itemPress="onPress" includeItemInSelection="true" mode="MultiSelect" items="{path: '/'}" id="Tree">
    <headerToolbar> 
       <Toolbar> 
          <content> 
             <Title level="H2" text="Title"/> 
             <ToolbarSpacer/> 
          </content> 
       </Toolbar>
    </headerToolbar>
    <StandardTreeItem title="{text}"/>
 </Tree>

I wanted to know if SAPUI5 had a property for its trees like "Check Children" or something similar. And if not, how could I do it.

Thanks.

2
  • create a custom TreeNode control with a checkbox property, and override the renderNode method in the sap.ui.commons.TreeRenderer class to display that checkbox when needed
    – Sahil Dhir
    Mar 31, 2017 at 11:35
  • but sap.ui.commons.TreeNode is deprecated since version 1.38
    – jiamep
    Mar 31, 2017 at 12:03

1 Answer 1

1

There are two approaches that come to mind:

  • Using binding (the 'better' way).
  • Using JS manipulation (the 'harder' way - because the TreeItem has no method for retrieving the child items).

I will show you the 'better' way for doing things. The 'harder' one you can do as an extension of this method (if you really want to go that way, I can also add info about how to do it).

Basically you need to extend your model by adding a selected flag. Assuming that you have a typical model structure (as in the explored example), you can use this function:

function addSelectedFlag(aNodes, bSelected) {
    jQuery.each(aNodes, function(iIndex, oNode) {
        oNode.selected = bSelected;
        if (oNode.nodes) {
            addSelectedFlag(oNode.nodes, bSelected);
        }
    });
}

Then, when the selection changes, you can do something along the lines of:

onSelect: function(oEvent) {
    var aItems = oEvent.getParameter("listItems") || [],
        oModel = this.getView().getModel();
    jQuery.each(aItems, function(iIndex, oItem) {
        var oNode = oItem.getBindingContext().getObject(),
            bSelected = oItem.getSelected();
        if (oNode.nodes) {
            addSelectedFlag(oNode.nodes, bSelected);
        }
    });
    oModel.refresh();
}

When you specify the template fro your item, you must also bind the selection:

<StandardTreeItem title="{text}" selected="{selected}"/>

I made a working JsFiddle out of this: https://jsfiddle.net/n4frtzd8/1/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.