I have a requirement to make a 3 level hierarchical table .

I have a requirement to make a 3 level hierarchical table .

Op_3Op_3 Posts: 1Questions: 1Answers: 0
edited January 9 in Free community support
var notificationMsg = (function () {
    var $processingMsgEl = $('#processingMsg'),
        _msg = 'Processing...',
        _stack = 0,
        _endTimeout;
    return {
        show: function (msg) {
            $processingMsgEl.text(msg || _msg);
            if (_stack === 0) {
                clearTimeout(_endTimeout);
                $processingMsgEl.show();
            }
            _stack++;
        },
        hide: function () {
            _stack--;
            if (_stack <= 0) {
                _stack = 0;
                clearTimeout(_endTimeout);
                _endTimeout = setTimeout(function () {
                    $processingMsgEl.hide();
                }, 500);
            }
        }
    }
})();

//Application ajax wrapper
function appAjax(processingMsg, ajaxOptions) {
    notificationMsg.show(processingMsg);
    return webapi.safeAjax(ajaxOptions)
        .fail(function (response) {
            if (response.responseJSON) {
                alert("Error: " + response.responseJSON.error.message)
            } else {
                alert("Error: Web API is not available... ")
            }
        }).always(notificationMsg.hide);
}

//Webapi ajax wrapper
(function (webapi, $) {
    function safeAjax(ajaxOptions) {
        var deferredAjax = $.Deferred();

        shell.getTokenDeferred().done(function (token) {
            // add headers for ajax
            if (!ajaxOptions.headers) {
                $.extend(ajaxOptions, {
                    headers: {
                        "__RequestVerificationToken": token
                    }
                });
            } else {
                ajaxOptions.headers["__RequestVerificationToken"] = token;
            }
            $.ajax(ajaxOptions)
                .done(function (data, textStatus, jqXHR) {
                    validateLoginSession(data, textStatus, jqXHR, deferredAjax.resolve);
                }).fail(deferredAjax.reject); //ajax
        }).fail(function () {
            deferredAjax.rejectWith(this, arguments); // on token failure, pass the token ajax and args
        });

        return deferredAjax.promise();
    }
    webapi.safeAjax = safeAjax;
})(window.webapi = window.webapi || {}, jQuery)

//API call to GET records
function loadRecords() {
    return appAjax('Loading...', {
        type: "GET",
        url: "/_api/sab_sampleproducts?$select=sab_sku,_sab_collectionsid_value,_sab_productgroupid_value",
        contentType: "application/json"
    });
}

var hdata = [];

// Add jQuery DataTables functionality to the product table
var prepareTable = function (productsContainer) {
    var table = productsContainer.children('table');

    table.DataTable({
        dom: "Bfrtip",
        "order": [[0, "asc"]],
        paging: false,
        info: false,
        searching: false,
        columnDefs: [
            { targets: 0, type: 'num' },
            { targets: [0, 1], visible: false },
            { orderable: false, targets: [2, 3, 4, 5, 6, 7] },
            {
                targets: 2, "createdCell": function (td, cellData, rowData, row, col) {
                    $(td).addClass('sku');
                }
            },
            {
                targets: 3, "createdCell": function (td, cellData, rowData, row, col) {
                    $(td).addClass('product-name');
                }
            },
            {
                targets: 5, "createdCell": function (td, cellData, rowData, row, col) {
                    $(td).addClass('max-quantity');
                }
            },
            {
                targets: 6, "createdCell": function (td, cellData, rowData, row, col) {
                    $(td).addClass('commentCell');
                }
            }
        ],
        columns: [
            { data: "ProductNumber", type: 'num' },
            { data: "DetailId" },
            { data: "ProductSku" },
            { data: "ProductName" },
            {
                data: "Quantity", "render": function (data, type, full, meta) {
                    var cellHtml = '<a href="#"  data-type="number" data-min="' + (full.ProductSku != null && full.Quantity == 0 ? '0' : full.Quantity) + '" data-pk="' + full.DetailId + '" data-url="/store/AddQuantityToDetail" data-title="Quantity" data-name="Quantity" class="editable-click quantity">' + (full.ProductSku != null && full.Quantity == 0 ? '0' : full.Quantity) + '</a></td>';
                    return cellHtml;
                },
                "width": "12%"
            },
            { data: "MaxQuantity" },
            {
                data: "Comments", "render": function (data, type, full, meta) {
                    var cellHtml = '<a href="#"  data-type="text" data-pk="' + full.DetailId + '" data-url="/Store/AddCommentToDetail" data-title="Comments" data-name="Comments" data-value="" class="editable-click editable-empty comment">' + (data == '' ? "no comment" : data) + '</a></td>';
                    return cellHtml;
                }
            },
            {
                "data": null,
                "defaultContent": "<a class=\"delete\" href=\"#\"><span class=\"t-icon t-delete\"></span></a>"
            }
        ],
        "createdRow": function (row, data, index) {
            // add the text boxes to the quick entry row
            if (data.ProductSku == null) {
                $(row).find('td.sku').html('<input type="text">');
                $(row).find('td.product-name').html('<input type="text">');
                $(row).find('td a.quantity').hide();
                $(row).find('td a.comment').hide();
            }
        }
    });

    // add inline editing to quantity and comment fields
    table.editable({
        tpl: '<input type="number">',
        selector: '.quantity',
        emptytext: '0',
        name: 'Quantity',
        validate: editableValidate,
        send: 'always'
    });

    table.editable({
        selector: '.comment',
        emptytext: 'no comment',
        name: 'Comments',
        send: 'always'
    });

    loadRecords().done(function (data) {
        table.data = _.map(data.value, function (record) {
            record.id = record.sab_sampleproductid;
            return record;
        });
        table.render($('#table_orders'));
    });
};

$(document).ready(function () {
    var collapsedGroups = [];
    var groupParent = [];
    var counter = 1;

    var table = $('#table_orders').DataTable({
        data: data,
        columns: [
            { data: '_sab_collectionsid_value', title: '_sab_collectionsid_value' },
            { data: '_sab_productgroupid_value', title: '_sab_productgroupid_value' },
            { data: 'sab_sku', title: 'sab_sku' },
        ],
        order: [[0, 'asc'], [1, 'asc'], [2, 'asc']],
        columnDefs: [{
            targets: [0, 1, 2],
            visible: false
        }],
        stripeClasses: [],
        paging: false,
        searching: false,
        rowGroup: {
            dataSrc: ['_sab_collectionsid_value', '_sab_productgroupid_value', 'sab_sku'],
            startRender: function (rows, group, level) {
                groupParent[level] = group;

                var groupAll = '';

                for (var i = 0; i < level; i++) {
                    groupAll += groupParent[i];

                    if (collapsedGroups[groupAll]) {
                        return;
                    }
                }
                groupAll += group;

                if ((typeof (collapsedGroups[groupAll]) == 'undefined') || (collapsedGroups[groupAll] === null)) { collapsedGroups[groupAll] = true; } //True = Start collapsed. False = Start expanded.

                var collapsed = collapsedGroups[groupAll];
                rows.nodes().each(function (r) { r.style.display = (collapsed ? 'none' : ''); });
                return $('<tr/>').append('<td>' + counter++ + ' ' + group + '</td>').append('<td></td>').attr('data-name', groupAll).toggleClass('collapsed', collapsed);
            },
            initComplete: function () {
                counter = 1;
            }
        }
    })
        .on('draw', function () {
            counter = 1;
        });


    $('#table_orders tbody').on('click', 'tr.dtrg-start', function () {
        var name = $(this).data('name');
        collapsedGroups[name] = !collapsedGroups[name];
        table.draw(false);
    });
});

var data = getResponse("https://sabertsampleportal.powerappsportals.com/_api/sab_sampleproducts?$select=sab_sku,_sab_collectionsid_value,_sab_productgroupid_value");

function getResponse(apiUrl) {
    var response = null;
    $.ajax({
        type: "GET",
        url: apiUrl,
        dataType: "json",
        async: false
    }).done(function (json) {
        response = json.value;
    });
    return response;
}

This is my code. In the last line, I want to add a table to show selection and I am not sure how to use the prepare table function.

Edited by Allan - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.

Answers

  • allanallan Posts: 62,990Questions: 1Answers: 10,367 Site admin

    Can you show me that running please? Others might be able to visualize what those 250 lines of code are doing with no other context, but I'm afraid I can't.

    Allan

Sign In or Register to comment.